Visit https://ebookultra.com to download the full version and
explore more ebooks
Developing Backbone js Applications Addy Osmani
_____ Click the link below to download _____
https://ebookultra.com/download/developing-backbone-js-
applications-addy-osmani/
Explore and download more ebooks at ebookultra.com
Here are some suggested products you might be interested in.
Click the link to download
Building Node Applications with MongoDB and Backbone 1st
Edition Mike Wilson
https://ebookultra.com/download/building-node-applications-with-
mongodb-and-backbone-1st-edition-mike-wilson/
Developing Mainframe Java Applications 1st Edition Lou
Marco
https://ebookultra.com/download/developing-mainframe-java-
applications-1st-edition-lou-marco/
Developing applications with enterprise SOA 1st Edition
Martin Huvar
https://ebookultra.com/download/developing-applications-with-
enterprise-soa-1st-edition-martin-huvar/
Enterprise J2ME developing mobile Java applications 8th
print Edition Yuan
https://ebookultra.com/download/enterprise-j2me-developing-mobile-
java-applications-8th-print-edition-yuan/
Developing Facebook Platform Applications with Rails 1st
Edition Michael J. Mangino
https://ebookultra.com/download/developing-facebook-platform-
applications-with-rails-1st-edition-michael-j-mangino/
Women Writing Africa West Africa and the Sahel Esi
Sutherland-Addy
https://ebookultra.com/download/women-writing-africa-west-africa-and-
the-sahel-esi-sutherland-addy/
Flask Web Development Developing Web Applications With
Python 2nd Edition Miguel Grinberg
https://ebookultra.com/download/flask-web-development-developing-web-
applications-with-python-2nd-edition-miguel-grinberg/
Developing Essbase Applications Hybrid Techniques and
Practices 2nd Edition Cameron Lackpour (Editor)
https://ebookultra.com/download/developing-essbase-applications-
hybrid-techniques-and-practices-2nd-edition-cameron-lackpour-editor/
Developing Android Applications with Adobe AIR 1st Edition
Véronique Brossier
https://ebookultra.com/download/developing-android-applications-with-
adobe-air-1st-edition-veronique-brossier/
Developing Backbone js Applications Addy Osmani
Digital Instant Download
Author(s): Addy Osmani
ISBN(s): 9781449328252, 1449328253
Edition: Early release
File Details: PDF, 2.54 MB
Year: 2012
Language: english
Developing Backbone.js
Applications
Addy Osmani
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
Developing Backbone.js Applications
by Addy Osmani
Revision History for the :
2012-04-19 Early release revision 1
See http://oreilly.com/catalog/errata.csp?isbn=9781449328252 for release details.
ISBN: 978-1-449-32825-2
1335306849
Table of Contents
Prelude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Fundamentals 2
MVC, MVP & Backbone.js 2
MVC 2
Smalltalk-80 MVC 2
MVC As We Know It 3
Models 4
Views 5
Controllers 8
Controllers in Spine.js vs Backbone.js 8
What does MVC give us? 10
Delving deeper 10
Summary 11
MVP 11
Models, Views & Presenters 11
MVP or MVC? 12
MVC, MVP and Backbone.js 13
Fast facts 15
Backbone.js 15
2. The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
What is Backbone? 17
Why should you consider using it? 17
The Basics 17
Models 18
Views 21
Creating new views 21
What is el? 22
Collections 23
iii
Underscore utility functions 25
Routers 25
Backbone.history 27
Namespacing 27
What is namespacing? 28
Additional Tips 31
Automated Backbone Scaffolding 31
Is there a limit to the number of routers I should be using? 32
Is Backbone too small for my application’s needs? 32
3. RESTful Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Building RESTful applications with Backbone 33
Stack 1: Building A Backbone App With Node.js, Express, Mongoose and
MongoDB 33
Reviewing the stack 33
Practical 34
Practical Setup 40
Building Backbone.js Apps With Ruby, Sinatra, MongoDB and Haml 42
Introduction 42
What Is Sinatra? 42
Getting Started With Sinatra 43
Templating And HAML 45
MongoDB Ruby Driver 47
Getting started 47
Practical 48
Installing The Prerequisites 48
Tutorial 50
Conclusions 57
4. Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Modular JavaScript 59
Organizing modules with RequireJS and AMD 59
Writing AMD modules with RequireJS 60
Keeping Your Templates External Using RequireJS And The Text Plugin 63
Optimizing Backbone apps for production with the RequireJS Optimizer 65
Practical: Building a modular Backbone app with AMD & RequireJS 67
Overview 67
Markup 68
Configuration options 69
Modularizing our models, views and collections 70
Decoupling Backbone with the Mediator and Facade patterns 75
Summary 75
Practical 76
iv | Table of Contents
Paginating Backbone.js Requests & Collections 82
Paginator’s pieces 83
Downloads And Source Code 83
Live Examples 84
Paginator.requestPager 86
1. Create a new Paginated collection 86
2: Set the model and base URL for the collection as normal 86
3. Map the attributes supported by your API (URL) 87
4. Configure the default pagination, query and sort details for the pag-
inator 87
5. Finally, configure Collection.parse() and we’re done 88
Convenience methods: 89
Paginator.clientPager 89
1. Create a new paginated collection with a model and URL 89
2. Map the attributes supported by your API (URL) 90
3. Configure how to paginate data at a UI-level 90
4. Configure the rest of the request parameter default values 90
5. Finally, configure Collection.parse() and we’re done 91
Convenience methods: 91
Views/Templates 91
Backbone & jQuery Mobile 94
Resolving the routing conflicts 94
Practical: A Backbone, RequireJS/AMD app with jQuery Mobile 95
Getting started 95
jQuery Mobile: Going beyond mobile application development 96
5. Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Unit Testing Backbone Applications With Jasmine 99
Introduction 99
Jasmine 99
Suites, Specs & Spies 101
beforeEach and afterEach() 104
Shared scope 104
Getting setup 105
TDD With Backbone 105
Models 105
Collections 108
Views 110
Initial setup 111
View rendering 113
Rendering with a templating system 116
Conclusions 118
Exercise 118
Table of Contents | v
Further reading 118
Unit Testing Backbone Applications With QUnit And SinonJS 119
Introduction 119
QUnit 119
Getting Setup 119
Assertions 120
Adding structure to assertions 124
Assertion examples 125
Fixtures 127
Asynchronous code 129
SinonJS 130
What is SinonJS? 130
Stubs and mocks 133
Practical 135
Models 135
Collections 137
Views 138
Events 139
App 141
Further Reading & Resources 142
6. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
7. Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
vi | Table of Contents
Prelude
Welcome to my (in-progress) book about the Backbone.js framework for structuring
JavaScript applications. It’s released under a Creative Commons Attribution-Non-
Commercial-ShareAlike 3.0 Unported license meaning you can both grab a copy of the
book for free or help to further improve it.
I’m very pleased to announce that this book will be out in physical form in a few months
time via O’Reilly Media. Readers will have the option of purchasing the latest version
in either print or a number of digital formats then or can grab a recent version from this
repository.
Corrections to existing material are always welcome and I hope that together we can
provide the community with an up-to-date resource that is of help. My extended thanks
go out to Jeremy Ashkenas for creating Backbone.js and these members of the com-
munity for their assistance tweaking this project.
I hope you find this book helpful!
vii
CHAPTER 1
Introduction
As JavaScript developers, we are at an interesting point in time where not only do we
have mature solutions to help organize the JavaScript powering our applications based
on a separation of concerns, but developers looking to build non-trivial projects are
almost spoiled for choice for frameworks that can help structure their applications.
Maturity in software (framework) development isn’t simply about how long a frame-
work has been around. It’s about how solid the framework is and more importantly
how well it’s evolved to fill its role. Has it become more effective at solving common
problems? Does it continue to improve as developers build larger and more complex
applications with it?
In this book, I will be covering the popular Backbone.js, which I consider the best of
the current family of JavaScript architectural frameworks.
Topics will include MVC theory and how to build applications using Backbone’s mod-
els, views, collections and routers. I’ll also be taking you through advanced topics like
modular development with Backbone.js and AMD (via RequireJS), how to build ap-
plications using modern software stacks (like Node and Express), how to solve the
routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and
a lot more.
If this is your first time looking at Backbone.js and you’re still unsure whether or not
to give it a try, why not take a look at how a Todo application can be implemented in
Backbone and several other popular Javascript frameworks before reading further?
The goal of this book is to create an authoritative and centralized repository of infor-
mation that can help those developing real-world apps with Backbone. If you come
across a section or topic which you think could be improved or expanded on, please
feel free to submit a pull-request. It won’t take long and you’ll be helping other devel-
opers avoid problems you’ve run into before.
1
Fundamentals
In this section we are going to cover the context into which a framework like Back-
bone.js fits. Let’s begin our journey into understanding Backbone better with a look at
code architecture.
MVC, MVP & Backbone.js
Before exploring any JavaScript frameworks that assist in structuring applications, it
can be useful to gain a basic understanding of architectural design patterns. Design
patterns are proven solutions to common development problems and can suggest
structural approaches to help guide developers in adding some organization to their
applications.
Patterns are useful because they’re a set of practices that build upon the collective
experience of skilled developers who have repeatedly solved similar problems. Al-
though developers 10 or 20 years ago may not have been using the same programming
languages when implementing patterns in their projects, there are many lessons we can
learn from their efforts.
In this section, we’re going to review two popular patterns - MVC and MVP. We’ll be
exploring in greater detail how Backbone.js implements these patterns shortly to better
appreciate where it fits in.
MVC
MVC (Model-View-Controller) is an architectural design pattern that encourages im-
proved application organization through a separation of concerns. It enforces the iso-
lation of business data (Models) from user interfaces (Views), with a third component
(Controllers) traditionally present to manage logic, user-input and the coordination of
models and views. The pattern was originally designed by Trygve Reenskaug while
working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-
Editor. MVC was described in depth in “Design Patterns: Elements of Reusable Object-
Oriented Software” (The “GoF” or “Gang of Four” book) in 1994, which played a role
in popularizing its use.
Smalltalk-80 MVC
It’s important to understand what the original MVC pattern was aiming to solve as it
has changed quite heavily since the days of its origin. Back in the 70’s, graphical user-
interfaces were far and few between. An approach known as Separated Presentation
began to be used as a means to make a clear division between domain objects which
modeled concepts in the real world (e.g a photo, a person) and the presentation objects
which were rendered to the user’s screen.
2 | Chapter 1: Introduction
The Smalltalk-80 implementation of MVC took this concept further and had an ob-
jective of separating out the application logic from the user interface. The idea was that
decoupling these parts of the application would also allow the reuse of models for other
interfaces in the application. There are some interesting points worth noting about
Smalltalk-80’s MVC architecture:
• A Domain element was known as a Model and were ignorant of the user-interface
(Views and Controllers)
• Presentation was taken care of by the View and the Controller, but there wasn’t
just a single view and controller. A View-Controller pair was required for each
element being displayed on the screen and so there was no true separation between
them
• The Controller’s role in this pair was handling user input (such as key-presses and
click events), doing something sensible with them.
• The Observer pattern was relied upon for updating the View whenever the Model
changed
Developers are sometimes surprised when they learn that the Observer pattern (nowa-
days commonly implemented as a Publish/Subscribe system) was included as a part of
MVC’s architecture decades ago. In Smalltalk-80’s MVC, the View and Controller both
observe the Model: anytime the Model changes, the Views react. A simple example of
this is an application backed by stock market data - for the application to show real-
time information, any change to the data in its Models should result in the View being
refreshed instantly.
Martin Fowler has done an excellent job of writing about the origins of MVC over the
years and if you are interested in further historical information about Smalltalk-80’s
MVC, I recommend reading his work.
MVC As We Know It
We’ve reviewed the 70’s, but let us now return to the here and now. The MVC pattern
has been applied to a diverse range of programming languages. For example, the pop-
ular Ruby on Rails is an implementation of a web application framework based on
MVC for the Ruby language. JavaScript now has a number of MVC frameworks, in-
cluding Ember.js, JavaScriptMVC, and of course Backbone.js. Given the importance
of avoiding “spaghetti” code, a term which describes code that is very difficult to read
or maintain due to its lack of structure, let’s look at what the MVC pattern enables the
Javascript developer to do.
MVC is composed of three core components:
MVC As We Know It | 3
Models
Models manage the data for an application. They are concerned with neither the user-
interface nor presentation layers, but instead represent structured data that an appli-
cation may require. When a model changes (e.g when it is updated), it will typically
notify its observers (e.g views, a concept we will cover shortly) that a change has oc-
curred so that they may react accordingly.
To understand models better, let us imagine we have a JavaScript photo gallery appli-
cation. In a photo gallery, a photo would merit its own model, as it represents a unique
kind of domain-specific data. The Photo model may represent attributes such as a
caption, image source and additional meta-data. A specific photo would be stored in
an instance of a model. Here’s an example of a simple Photo model implemented with
Backbone.js:
var Photo = Backbone.Model.extend({
// Default attributes for the photo
defaults: {
// Ensure that each photo created has an `src`.
src: "placeholder.jpg",
caption: "A default image",
viewed: false
},
initialize: function() {
}
});
The built-in capabilities of models vary across frameworks, however it’s common for
them to support validation of attributes, where attributes represent the properties of
the model, such as a model identifier. When using models in real-world applications
we generally also need a way of persisting models. Persistence allows us to edit and
update models with the knowledge that their most recent states will be saved some-
where, for example in a web browser’s localStorage data-store or synchronized with a
database.
A model may also have multiple views observing it. Imagine our Photo model contained
meta-data such as the longitude and latitude where the photo was taken, a list of people
present in the photo, and a list of tags. A developer could create a single view that
displayed all these attributes, or might create three separate views to display each at-
tribute. The important detail is that the Photo model doesn’t care how these views are
organized, it simply announces updates to its data as necessary. We’ll come back to
Views in more detail later.
It is not uncommon for modern MVC/MV* frameworks to provide a means to group
models together. In Backbone, these groups are called “Collections”. Managing models
in groups allows us to write application logic based on notifications from the group,
4 | Chapter 1: Introduction
should any model it contains change. This avoids the need to manually observe indi-
vidual model instances.
Here’s how we might group Photo models into a simplified Backbone Collection:
var PhotoGallery = Backbone.Collection.extend({
// Reference to this collection's model.
model: Photo,
// Filter down the list of all photos that have been viewed
viewed: function() {
return this.filter(function(photo){ return photo.get('viewed'); });
},
// Filter down the list to only photos that have not yet been viewed
unviewed: function() {
return this.without.apply(this, this.viewed());
}
});
If you read older texts on MVC, you may come across a description of models as also
managing application “state”. In JavaScript applications “state” has a specific meaning,
typically referring to the current “state” of a view or sub-view on a user’s screen at a
fixed time. State is a topic which is regularly discussed when looking at Single-page
applications, where the concept of state needs to be simulated.
Views
Views are a visual representation of models that present a filtered view of their current
state. A view typically observes a model and is notified when the model changes, al-
lowing the view to update itself accordingly. Design pattern literature commonly refers
to views as “dumb”, given that their knowledge of models and controllers in an appli-
cation is limited.
Users interact with views, which usually means reading and editing model data. For
example, in our photo gallery application example, model viewing might happen in a
user interface with a big image, a caption, and a list of tags. Model editing could be
done through an “edit” view where a user who has selected a specific photo could edit
its caption, tags, or other metadata in a form.
In MVC, the actual task of updating the Model falls to Controllers, which we’ll be
covering shortly.
Let’s explore Views a little further using a simple JavaScript example. Below we can see
a function that creates a single Photo view, consuming both a model instance and a
controller instance.
MVC As We Know It | 5
We define a render() utility within our view which is responsible for rendering the
contents of the photoModel using a JavaScript templating engine (Underscore templat-
ing) and updating the contents of our view, referenced by photoEl.
The photoModel then adds our render() callback as one of its subscribers, so that
through the Observer pattern it can trigger the view to update when the model changes.
You may wonder where user interaction comes into play here. When users click on any
elements within the view, it’s not the view’s responsibility to know what to do next. A
Controller makes this decision. In our sample implementation, this is achieved by
adding an event listener to photoEl which will delegate handling the click behavior back
to the controller, passing the model information along with it in case it’s needed.
The benefit of this architecture is that each component plays its own separate role in
making the application function as needed.
var buildPhotoView = function( photoModel, photoController ){
var base = document.createElement('div'),
photoEl = document.createElement('div');
base.appendChild(photoEl);
var render= function(){
// We use a templating library such as Underscore
// templating which generates the HTML for our
// photo entry
photoEl.innerHTML = _.template('photoTemplate', {src: photoModel.getSrc()});
}
photoModel.addSubscriber( render );
photoEl.addEventListener('click', function(){
photoController.handleEvent('click', photoModel );
});
var show = function(){
photoEl.style.display = '';
}
var hide = function(){
photoEl.style.display = 'none';
}
return{
showView: show,
hideView: hide
}
}
Templating
6 | Chapter 1: Introduction
In the context of JavaScript frameworks that support MVC/MV*, it is worth looking
more closely at JavaScript templating and its relationship to Views.
It has long been considered bad practice (and computationally expensive) to manually
create large blocks of HTML markup in-memory through string concatenation. De-
velopers using this technique often find themselves iterating through their data, wrap-
ping it in nested divs and using outdated techniques such as document.write to inject
the “template” into the DOM. This approach often means keeping scripted markup
inline with standard markup, which can quickly become difficult to read and maintain,
especially when building large applications.
JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to
define templates for views as HTML markup containing template variables. These
template blocks can be either stored externally or within script tags with a custom type
(e.g “text/template”). Variables are delimited using a variable syntax (e.g {{name}}).
Javascript template libraries typically accept data in JSON, and the grunt work of pop-
ulating templates with data is taken care of by the framework itself. This has a several
benefits, particularly when opting to store templates externally as this can let applica-
tions load templates dynamically on an as-needed basis.
Let’s compare two examples of HTML templates. One is implemented using the pop-
ular Handlebars.js library, and the other uses Underscore’s “microtemplates”.
Handlebars.js:
<li class="photo">
<h2>{{caption}}</h2>
<img class="source" src="{{src}}"/>
<div class="meta-data">
{{metadata}}
</div>
</li>
Underscore.js Microtemplates:
<li class="photo">
<h2><%= caption %></h2>
<img class="source" src="<%= src %>"/>
<div class="meta-data">
<%= metadata %>
</div>
</li>
You may also use double curly brackets (i.e {{}}) (or any other tag you feel comfortable
with) in Microtemplates. In the case of curly brackets, this can be done by setting the
Underscore templateSettings attribute as follows:
_.templateSettings = { interpolate : /{{(.+?)}}/g };
A note on navigation and state
It is also worth noting that in classical web development, navigating between inde-
pendent views required the use of a page refresh. In single-page JavaScript applications,
MVC As We Know It | 7
however, once data is fetched from a server via Ajax, it can be dynamically rendered in
a new view within the same page. Since this doesn’t automatically update the URL, the
role of navigation thus falls to a “router”, which assists in managing application state
(e.g allowing users to bookmark a particular view they have navigated to). As routers
are however neither a part of MVC nor present in every MVC-like framework, I will
not be going into them in greater detail in this section.
Controllers
Controllers are an intermediary between models and views which are classically re-
sponsible for two tasks: they both update the view when the model changes and update
the model when the user manipulates the view.
In our photo gallery application, a controller would be responsible for handling changes
the user made to the edit view for a particular photo, updating a specific photo model
when a user has finished editing.
It’s with controllers that most JavaScript MVC frameworks depart from this interpre-
tation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript
framework authors likely initially looked at server-side interpretations of MVC (such
as Ruby on Rails), realized that that approach didn’t translate 1:1 on the client-side,
and so re-interpreted the C in MVC to solve their state management problem. This was
a clever approach, but it can make it hard for developers coming to MVC for the first
time to understand both the classical MVC pattern and the “proper” role of controllers
in other non-Javascript frameworks.
So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain
“controller” logic, and Routers (discussed below) are used to help manage application
state, but neither are true Controllers according to classical MVC.
In this respect, contrary to what might be mentioned in the official documentation or
in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It’s in
fact better to see it a member of the MV* family which approaches architecture in its
own way. There is of course nothing wrong with this, but it is important to distinguish
between classical MVC and MV* should you be relying on discussions of MVC to help
with your Backbone projects.
Controllers in Spine.js vs Backbone.js
Spine.js
We now know that controllers are traditionally responsible for updating the view when
the model changes (and similarly the model when the user updates the view). Since
Backbone doesn’t have its own explicit controllers, it’s useful to review the controller
from another MVC framework to appreciate the difference in implementations. Let’s
take a look at Spine.js:
8 | Chapter 1: Introduction
In this example, we’re going to have a controller called PhotosController which will be
in charge of individual photos in the application. It will ensure that when the view
updates (e.g a user edited the photo meta-data) the corresponding model does too.
(Note: We won’t be delving heavily into Spine.js beyond this example, but it’s worth
looking at it to learn more about Javascript frameworks in general.)
// Controllers in Spine are created by inheriting from Spine.Controller
var PhotosController = Spine.Controller.sub({
init: function(){
this.item.bind("update", this.proxy(this.render));
this.item.bind("destroy", this.proxy(this.remove));
},
render: function(){
// Handle templating
this.replace($("#photoTemplate").tmpl(this.item));
return this;
},
remove: function(){
this.$el.remove();
this.release();
}
});
In Spine, controllers are considered the glue for an application, adding and responding
to DOM events, rendering templates and ensuring that views and models are kept in
sync (which makes sense in the context of what we know to be a controller).
What we’re doing in the above example is setting up listeners in the update and
destroy events using render() and remove(). When a photo entry gets updated, we re-
render the view to reflect the changes to the meta-data. Similarly, if the photo gets
deleted from the gallery, we remove it from the view. In case you were wondering about
the tmpl() function in the code snippet: in the render() function, we’re using this to
render a JavaScript template called #photoTemplate which simply returns a HTML
string used to replace the controller’s current element.
Whatthisprovidesuswithisaverylightweight,simplewaytomanagechangesbetween
the model and the view.
Backbone.js
Later on in this section we’re going to revisit the differences between Backbone and
traditional MVC, but for now let’s focus on controllers.
In Backbone, controller logic is shared between Backbone.View and Backbone.Router.
Earlier releases of Backbone contained something called Backbone.Controller, but it
was renamed to Router to clarify its role.
A Router’s main purpose is to translate URL requests into application states. When a
user browses to the URL www.example.com/photos/42, a Router could be used to
MVC As We Know It | 9
show the photo with that ID, and to define what application behavior should be run
in response to that request. Routers can contain traditional controller responsibilities,
such as binding the events between models and views, or rendering parts of the page.
However, Backbone contributor Tim Branyen has pointed out that it’s possible to get
away without needing Backbone.Router at all for this, so a way to think about it using
the Router paradigm is probably:
var PhotoRouter = Backbone.Router.extend({
routes: { "photos/:id": "route" },
route: function(id) {
var item = photoCollection.get(id);
var view = new PhotoView({ model: item });
something.html( view.render().el );
}
}):
What does MVC give us?
To summarize, the separation of concerns in MVC facilitates modularization of an
application’s functionality and enables:
• Easier overall maintenance. When updates need to be made to the application it
is clear whether the changes are data-centric, meaning changes to models and pos-
sibly controllers, or merely visual, meaning changes to views.
• Decoupling models and views means that it’s straight-forward to write unit tests
for business logic
• Duplication of low-level model and controller code is eliminated across the appli-
cation
• Depending on the size of the application and separation of roles, this modularity
allows developers responsible for core logic and developers working on the user-
interfaces to work simultaneously
Delving deeper
Right now, you likely have a basic understanding of what the MVC pattern provides,
but for the curious, we’ll explore it a little further.
The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider
it a “set of classes to build a user interface”. In their view, it’s actually a variation of
three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite
patterns. Depending on how MVC has been implemented in a framework, it may also
use the Factory and Decorator patterns. I’ve covered some of these patterns in my other
free book, JavaScript Design Patterns For Beginners if you would like to read into them
further.
10 | Chapter 1: Introduction
As we’ve discussed, models represent application data, while views handle what the
user is presented on screen. As such, MVC relies on Pub/Sub for some of its core com-
munication (something that surprisingly isn’t covered in many articles about the MVC
pattern). When a model is changed it “publishes” to the rest of the application that it
has been updated. The “subscriber”–generally a Controller–then updates the view ac-
cordingly. The observer-viewer nature of this relationship is what facilitates multiple
views being attached to the same model.
For developers interested in knowing more about the decoupled nature of MVC (once
again, depending on the implementation), one of the goals of the pattern is to help
define one-to-many relationships between a topic and its observers. When a topic
changes, its observers are updated. Views and controllers have a slightly different re-
lationship. Controllers facilitate views to respond to different user input and are an
example of the Strategy pattern.
Summary
Having reviewed the classical MVC pattern, your should now understand how it allows
developers to cleanly separate concerns in an application. You should also now appre-
ciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and
how they share some of the fundamental concepts of the original pattern.
When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful
to step back and consider how it’s opted to approach Models, Views, Controllers or
other alternatives, as this can better help you grok how the framework expects to be
used.
MVP
Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses
on improving presentation logic. It originated at a company named Taligent in the early
1990s while they were working on a model for a C++ CommonPoint environment.
Whilst both MVC and MVP target the separation of concerns across multiple compo-
nents, there are some fundamental differences between them.
For the purposes of this summary we will focus on the version of MVP most suitable
for web-based architectures.
Models, Views & Presenters
The P in MVP stands for presenter. It’s a component which contains the user-interface
business logic for the view. Unlike MVC, invocations from the view are delegated to
the presenter, which are decoupled from the view and instead talk to it through an
interface. This allows for all kinds of useful things such as being able to mock views in
unit tests.
MVP | 11
The most common implementation of MVP is one which uses a Passive View (a view
which is for all intents and purposes “dumb”), containing little to no logic. MVP models
are almost identical to MVC models and handle application data. The presenter acts
asamediatorwhichtalkstoboththeviewandmodel,howeverbothoftheseareisolated
from each other. They effectively bind models to views, a responsibility held by Con-
trollers in MVC. Presenters are at the heart of the MVP pattern and as you can guess,
incorporate the presentation logic behind views.
Solicited by a view, presenters perform any work to do with user requests and pass data
back to them. In this respect, they retrieve data, manipulate it and determine how the
data should be displayed in the view. In some implementations, the presenter also
interacts with a service layer to persist data (models). Models may trigger events but
it’s the presenter’s role to subscribe to them so that it can update the view. In this passive
architecture, we have no concept of direct data binding. Views expose setters which
presenters can use to set data.
The benefit of this change from MVC is that it increases the testability of your appli-
cation and provides a more clean separation between the view and the model. This isn’t
however without its costs as the lack of data binding support in the pattern can often
mean having to take care of this task separately.
Although a common implementation of a Passive View is for the view to implement an
interface, there are variations on it, including the use of events which can decouple the
View from the Presenter a little more. As we don’t have the interface construct in Java-
Script, we’re using it more as more a protocol than an explicit interface here. It’s tech-
nically still an API and it’s probably fair for us to refer to it as an interface from that
perspective.
There is also a Supervising Controller variation of MVP, which is closer to the MVC
and MVVM patterns as it provides data-binding from the Model directly from the View.
Key-value observing (KVO) plugins (such as Derick Bailey’s Backbone.ModelBinding
plugin) introduce this idea of a Supervising Controller to Backbone.
MVP or MVC?
MVP is generally used most often in enterprise-level applications where it’s necessary
to reuse as much presentation logic as possible. Applications with very complex views
and a great deal of user interaction may find that MVC doesn’t quite fit the bill here as
solving this problem may mean heavily relying on multiple controllers. In MVP, all of
this complex logic can be encapsulated in a presenter, which can simplify maintenance
greatly.
As MVP views are defined through an interface and the interface is technically the only
point of contact between the system and the view (other than a presenter), this pattern
also allows developers to write presentation logic without needing to wait for designers
to produce layouts and graphics for the application.
12 | Chapter 1: Introduction
Depending on the implementation, MVP may be more easy to automatically unit test
than MVC. The reason often cited for this is that the presenter can be used as a complete
mock of the user-interface and so it can be unit tested independent of other compo-
nents. In my experience this really depends on the languages you are implementing
MVP in (there’s quite a difference between opting for MVP for a JavaScript project over
one for say, ASP.net).
At the end of the day, the underlying concerns you may have with MVC will likely hold
true for MVP given that the differences between them are mainly semantic. As long as
you are cleanly separating concerns into models, views and controllers (or presenters)
you should be achieving most of the same benefits regardless of the pattern you opt for.
MVC, MVP and Backbone.js
There are very few, if any architectural JavaScript frameworks that claim to implement
the MVC or MVP patterns in their classical form as many JavaScript developers don’t
view MVC and MVP as being mutually exclusive (we are actually more likely to see
MVP strictly implemented when looking at web frameworks such as ASP.net or GWT).
This is because it’s possible to have additional presenter/view logic in your application
and yet still consider it a flavor of MVC.
Backbone contributor Irene Ros subscribes to this way of thinking as when she sepa-
rates Backbone views out into their own distinct components, she needs something to
actually assemble them for her. This could either be a controller route (such as a Back
bone.Router, covered later in the book) or a callback in response to data being fetched.
That said, some developers do however feel that Backbone.js better fits the description
of MVP than it does MVC . Their view is that:
• The presenter in MVP better describes the Backbone.View (the layer between View
templates and the data bound to it) than a controller does
• The model fits Backbone.Model (it isn’t that different from the classical MVC
“Model”)
• The views best represent templates (e.g Handlebars/Mustache markup templates)
A response to this could be that the view can also just be a View (as per MVC) because
Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and
the P in MVP can both be accomplished by Backbone.View because they’re able to ach-
ieve two purposes: both rendering atomic components and assembling those compo-
nents rendered by other views.
We’ve also seen that in Backbone the responsibility of a controller is shared with both
the Backbone.View and Backbone.Router and in the following example we can actually
see that aspects of that are certainly true.
MVC, MVP and Backbone.js | 13
Here, our Backbone PhotoView uses the Observer pattern to “subscribe” to changes to
a View’s model in the line this.model.on('change',...). It also handles templating in
the render() method, but unlike some other implementations, user interaction is also
handled in the View (see events).
var PhotoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Pass the contents of the photo template through a templating
// function, cache it for a single photo
template: _.template($('#photo-template').html()),
// The DOM events specific to an item.
events: {
"click img" : "toggleViewed"
},
// The PhotoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Photo** and a **PhotoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
_.bindAll(this, 'render');
this.model.on('change', this.render);
this.model.on('destroy', this.remove);
},
// Re-render the photo entry
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
// Toggle the `"viewed"` state of the model.
toggleViewed: function() {
this.model.viewed();
}
});
Another (quite different) opinion is that Backbone more closely resembles Smalltalk-80
MVC, which we went through earlier.
As regular Backbone user Derick Bailey has written, it’s ultimately best not to force
Backbone to fit any specific design patterns. Design patterns should be considered
flexible guides to how applications may be structured and in this respect, Backbone
doesn’t fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts
from multiple architectural patterns and creates a flexible framework that just works
well. Call it the Backbone way, MV* or whatever helps reference its flavor of appli-
cation architecture.
14 | Chapter 1: Introduction
It is however worth understanding where and why these concepts originated, so I hope
that my explanations of MVC and MVP have been of help. Most structural JavaScript
frameworks will adopt their own take on classical patterns, either intentionally or by
accident, but the important thing is that they help us develop applications which are
organized, clean and can be easily maintained.
Fast facts
Backbone.js
• Core components: Model, View, Collection, Router. Enforces its own flavor of
MV*
• Good documentation, with more improvements on the way
• Used by large companies such as SoundCloud and Foursquare to build non-trivial
applications
• Event-driven communicationbetweenviewsandmodels. Aswe’llsee,it’srelatively
straight-forwardtoaddeventlistenerstoanyattributeinamodel,givingdevelopers
fine-grained control over what changes in the view
• Supports data bindings through manual events or a separate Key-value observing
(KVO) library
• Great support for RESTful interfaces out of the box, so models can be easily tied
to a backend
• Extensive eventing system. It’s trivial to add support for pub/sub in Backbone
• Prototypes are instantiated with the new keyword, which some developers prefer
• Agnostic about templating frameworks, however Underscore’s micro-templating
is available by default. Backbone works well with libraries like Handlebars
• Doesn’t support deeply nested models, though there are Backbone plugins such as
this which can help
• Clear and flexible conventions for structuring applications. Backbone doesn’t force
usage of all of its components and can work with only those needed.
Fast facts | 15
CHAPTER 2
The Basics
What is Backbone?
Backbone.js is one of a number of JavaScript frameworks for creating MVC-like web
applications. On the front-end, it’s my architectural framework of choice as it’s both
mature, relatively lightweight and can be easily tested using third-party toolkits such
as Jasmine or QUnit. Other MVC frameworks you may be familiar with include Em-
ber.js (SproutCore 2.0), Spine, YUILibrary and JavaScriptMVC.
Backbone is maintained by a number of contributors, most notably: Jeremy Ashkenas,
creator of CoffeeScript, Docco and Underscore.js. As Jeremy is a believer in detailed
documentation, there’s a level of comfort in knowing you’re unlikely to run into issues
which are either not explained in the official docs or which can’t be nailed down with
some assistance from the #documentcloud IRC channel. I strongly recommend using
the latter if you find yourself getting stuck.
Why should you consider using it?
Backbone’s main benefits, regardless of your target platform or device, include helping:
• Organize the structure to your application
• Simplify server-side persistence
• Decouple the DOM from your page’s data
• Model data, views and routers in a succinct manner
• Provide DOM, model and collection synchronization
The Basics
In this section, you’ll learn the essentials of Backbone’s models, views, collections and
routers, as well as about using namespacing to organize your code. This isn’t meant as
17
a replacement for the official documentation, but it will help you understand many of
the core concepts behind Backbone before you start building applications with it.
• Models
• Collections
• Routers
• Views
• Namespacing
Models
Backbone models contain interactive data for an application as well as the logic around
this data. For example, we can use a model to represent the concept of a photo object
including its attributes like tags, titles and a location.
Models can be created by extending Backbone.Model as follows:
var Photo = Backbone.Model.extend({
defaults: {
src: 'placeholder.jpg',
title: 'an image placeholder',
coordinates: [0,0]
},
initialize: function(){
this.on("change:src", function(){
var src = this.get("src");
console.log('Image source updated to ' + src);
});
},
changeSrc: function( source ){
this.set({ src: source });
}
});
var somePhoto = new Photo({ src: "test.jpg", title:"testing"});
somePhoto.changeSrc("magic.jpg"); // which triggers "change:src" and logs an update message to the conso
Initialization
The initialize() method is called when a new instance of a model is created. Its use
is optional, however you’ll see why it’s good practice to use it below.
var Photo = Backbone.Model.extend({
initialize: function(){
console.log('this model has been initialized');
}
});
// We can then create our own instance of a photo as follows:
var myPhoto = new Photo();
18 | Chapter 2: The Basics
Getters & Setters
Model.get()
Model.get() provides easy access to a model’s attributes. Attributes which are passed
through to the model on instantiation are instantly available for retrieval.
var myPhoto = new Photo({ title: "My awesome photo",
src:"boston.jpg",
location: "Boston",
tags:['the big game', 'vacation']}),
title = myPhoto.get("title"), //My awesome photo
location = myPhoto.get("location"), //Boston
tags = myPhoto.get("tags"), // ['the big game','vacation']
photoSrc = myPhoto.get("src"); //boston.jpg
Alternatively, if you wish to directly access all of the attributes in a model’s instance
directly, you can achieve this as follows:
var myAttributes = myPhoto.attributes;
console.log(myAttributes);
It is best practice to use Model.set() or direct instantiation to set the values of a model’s
attributes.
Accessing Model.attributes directly is generally discouraged. Instead, should you need
to read or clone data, Model.toJSON() is recommended for this purpose. If you would
like to access or copy a model’s attributes for purposes such as JSON stringification
(e.g. for serialization prior to being passed to a view), this can be achieved using
Model.toJSON():
var myAttributes = myPhoto.toJSON();
console.log(myAttributes);
/* this returns { title: "My awesome photo",
src:"boston.jpg",
location: "Boston",
tags:['the big game', 'vacation']}*/
Model.set()
Model.set() allows us to pass attributes into an instance of our model. Attributes can
either be set during initialization or at any time afterwards. It’s important to avoid trying
to set a Model’s attributes directly (for example Model.caption = “A new caption”).
Backbone uses Model.set() to know when to broadcast that a model’s data has changed.
var Photo = Backbone.Model.extend({
initialize: function(){
console.log('this model has been initialized');
}
});
// Setting the value of attributes via instantiation
var myPhoto = new Photo({ title: 'My awesome photo', location: 'Boston' });
The Basics | 19
var myPhoto2 = new Photo();
// Setting the value of attributes through Model.set()
myPhoto2.set({ title:'Vacation in Florida', location: 'Florida' });
Default values
There are times when you want your model to have a set of default values (e.g. in a
scenario where a complete set of data isn’t provided by the user). This can be set using
a property called defaults in your model.
var Photo = Backbone.Model.extend({
defaults:{
title: 'Another photo!',
tags: ['untagged'],
location: 'home',
src: 'placeholder.jpg'
},
initialize: function(){
}
});
var myPhoto = new Photo({ location: "Boston",
tags:['the big game', 'vacation']}),
title = myPhoto.get("title"), //Another photo!
location = myPhoto.get("location"), //Boston
tags = myPhoto.get("tags"), // ['the big game','vacation']
photoSrc = myPhoto.get("src"); //placeholder.jpg
Listening for changes to your model
Any and all of the attributes in a Backbone model can have listeners bound to them
which detect when their values change. Listeners can be added to the initialize()
function:
this.on('change', function(){
console.log('values for this model have changed');
});
In the following example, we log a message whenever a specific attribute (the title of
our Photo model) is altered.
var Photo = Backbone.Model.extend({
defaults:{
title: 'Another photo!',
tags: ['untagged'],
location: 'home',
src: 'placeholder.jpg'
},
initialize: function(){
console.log('this model has been initialized');
this.on("change:title", function(){
var title = this.get("title");
console.log("My title has been changed to.. " + title);
});
},
20 | Chapter 2: The Basics
setTitle: function(newTitle){
this.set({ title: newTitle });
}
});
var myPhoto = new Photo({ title:"Fishing at the lake", src:"fishing.jpg"});
myPhoto.setTitle('Fishing at sea');
//logs 'My title has been changed to.. Fishing at sea'
Validation
BackbonesupportsmodelvalidationthroughModel.validate(),whichallowschecking
the attribute values for a model prior to them being set.
Validationfunctions canbeassimpleorcomplex asnecessary.Iftheattributesprovided
are valid, nothing should be returned from .validate(). If they are invalid, a custom
error can be returned instead.
A basic example for validation can be seen below:
var Photo = Backbone.Model.extend({
validate: function(attribs){
if(attribs.src === undefined){
return "Remember to set a source for your image!";
}
},
initialize: function(){
console.log('this model has been initialized');
this.on("error", function(model, error){
console.log(error);
});
}
});
var myPhoto = new Photo();
myPhoto.set({ title: "On the beach" });
//logs Remember to set a source for your image!
Views
Views in Backbone don’t contain the markup for your application, but rather they are
there to support models by defining the logic for how they should be represented to
the user. This is usually achieved using JavaScript templating (e.g. Mustache, jQuery-
tmpl, etc.). A view’s render() function can be bound to a model’s change() event, al-
lowing the view to always be up to date without requiring a full page refresh.
Creating new views
Similar to the previous sections, creating a new view is relatively straight-forward. To
create a new View, simply extend Backbone.View. I’ll explain this code in detail below:
Views | 21
var PhotoSearch = Backbone.View.extend({
el: $('#results'),
render: function( event ){
var compiled_template = _.template( $("#results-template").html() );
this.$el.html( compiled_template(this.model.toJSON()) );
return this; //recommended as this enables calls to be chained.
},
events: {
"submit #searchForm": "search",
"click .reset": "reset",
"click .advanced": "switchContext"
},
search: function( event ){
//executed when a form '#searchForm' has been submitted
},
reset: function( event ){
//executed when an element with class "reset" has been clicked.
},
switchContext: function( event ){
//executed when an element with class "advanced" has been clicked.
}
});
What is el?
el is basically a reference to a DOM element and all views must have one. It allows for
all of the contents of a view to be inserted into the DOM at once, which makes for faster
rendering as browser performs the minimum required reflows and repaints.
There are two ways to attach a DOM element to a view: the element already exists in
the page or a new element is created for the view and added manually by the developer.
If the element already exists in the page, you can set el as either a CSS selector that
matches the element or a simple reference to the DOM element.
el: '#footer',
// OR
el: document.getElementById( 'footer' )
If you want to create a new element for your view, set any combination of the following
view’s properties: tagName, id and className. A new element will be created for you by
the framework and a reference to it will be available at the el property.
tagName: 'p', // required, but defaults to 'div' if not set
className: 'container', // optional, you can assign multiple classes to this property like so 'container
id: 'header', // optional
The above code creates the DOMElement below but doesn’t append it to the DOM.
<p id="header" class="container"></p>
Understanding render()
22 | Chapter 2: The Basics
render() is an optional function that defines the logic for rendering a template. We’ll
use Underscore’s micro-templating in these examples, but remember you can use other
templating frameworks if you prefer.
The _.template method in Underscore compiles JavaScript templates into functions
which can be evaluated for rendering. In the above view, I’m passing the markup from
a template with id results-template to _.template() to be compiled. Next, I set the
html of the el DOM element to the output of processing a JSON version of the model
associated with the view through the compiled template.
Presto! This populates the template, giving you a data-complete set of markup in just
a few short lines of code.
The events attribute
The Backbone events attribute allows us to attach event listeners to either custom
selectors, or directly to el if no selector is provided. An event takes the form {"eventName
selector": "callbackFunction"} and a number of event-types are supported, including
click, submit, mouseover, dblclick and more.
What isn’t instantly obvious is that under the bonnet, Backbone uses jQuery’s .dele
gate() toprovideinstantsupportforeventdelegationbutgoesalittlefurther,extending
it so that this always refers to the current view object. The only thing to really keep in
mind is that any string callback supplied to the events attribute must have a corre-
sponding function with the same name within the scope of your view.
Collections
Collections are sets of Models and are created by extending Backbone.Collection.
Normally, when creating a collection you’ll also want to pass through a property spec-
ifying the model that your collection will contain, as well as any instance properties
required.
In the following example, we create a PhotoCollection that will contain our Photo
models:
var PhotoCollection = Backbone.Collection.extend({
model: Photo
});
Getters and Setters
There are a few different ways to retrieve a model from a collection. The most straight-
forward is to use Collection.get() which accepts a single id as follows:
var skiingEpicness = PhotoCollection.get(2);
Sometimes you may also want to get a model based on its client id. The client id is a
property that Backbone automatically assigns models that have not yet been saved. You
can get a model’s client id from its .cid property.
Collections | 23
var mySkiingCrash = PhotoCollection.getByCid(456);
Backbone Collections don’t have setters as such, but do support adding new models
via .add() and removing models via .remove().
var a = new Backbone.Model({ title: 'my vacation'}),
b = new Backbone.Model({ title: 'my holiday'});
var photoCollection = new PhotoCollection([a,b]);
photoCollection.remove([a,b]);
Listening for events
As collections represent a group of items, we’re also able to listen for add and remove
events for when new models are added or removed from the collection. Here’s an ex-
ample:
var PhotoCollection = new Backbone.Collection();
PhotoCollection.on("add", function(photo) {
console.log("I liked " + photo.get("title") + ' its this one, right? ' + photo.get("src"));
});
PhotoCollection.add([
{title: "My trip to Bali", src: "bali-trip.jpg"},
{title: "The flight home", src: "long-flight-oofta.jpg"},
{title: "Uploading pix", src: "too-many-pics.jpg"}
]);
In addition, we’re able to bind a change event to listen for changes to models in the
collection.
PhotoCollection.on("change:title", function(){
console.log('there have been updates made to this collections titles');
});
Fetching models from the server
Collections.fetch() retrieves a default set of models from the server in the form of a
JSON array. When this data returns, the current collection’s contents will be replaced
with the contents of the array.
var PhotoCollection = new Backbone.Collection;
PhotoCollection.url = '/photos';
PhotoCollection.fetch();
Under the covers, Backbone.sync is the function called every time Backbone tries to read
or save models to the server. It uses jQuery or Zepto’s ajax implementations to make
these RESTful requests, however this can be overridden as per your needs.
In the above example if we wanted to log an event when .sync() was called, we could
do this:
Backbone.sync = function(method, model) {
console.log("I've been passed " + method + " with " + JSON.stringify(model));
};
24 | Chapter 2: The Basics
Resetting/Refreshing Collections
Rather than adding or removing models individually, you might occasionally wish to
update an entire collection at once. Collection.reset() allows us to replace an entire
collection with new models as follows:
javascript PhotoCollection.reset([ {title: "My trip to Scotland", src: "scot
land-trip.jpg"}, {title: "The flight from Scotland", src: "long-flight.jpg"},
{title: "Latest snap of lock-ness", src: "lockness.jpg"}]); Note that using Col
lection.reset() doesn’t fire any add or remove events. A reset event is fired instead.
Underscore utility functions
As Backbone requires Underscore as a hard dependency, we’re able to use many of the
utilities it has to offer to aid with our application development. Here’s an example of
how Underscore’s sortBy() method can be used to sort a collection of photos based
on a particular attribute.
var sortedByAlphabet = PhotoCollection.sortBy(function (photo) {
return photo.get("title").toLowerCase();
});
The complete list of what Underscore can do is beyond the scope of this guide, but can
be found in its official docs.
Routers
In Backbone, routers are used to help manage application state and for connecting
URLs to application events. This is achieved using hash-tags with URL fragments, or
using the browser’s pushState and History API. Some examples of routes may be seen
below:
http://unicorns.com/#whatsup
http://unicorns.com/#search/seasonal-horns/page2
Note: An application will usually have at least one route mapping a URL route to a
function that determines what happens when a user reaches that particular route. This
relationship is defined as follows:
"route" : "mappedFunction"
Let us now define our first controller by extending Backbone.Router. For the purposes
of this guide, we’re going to continue pretending we’re creating a photo gallery appli-
cation that requires a GalleryRouter.
Note the inline comments in the code example below as they continue the rest of the
lesson on routers.
var GalleryRouter = Backbone.Router.extend({
/* define the route and function maps for this router */
Routers | 25
routes: {
"about" : "showAbout",
/*Sample usage: http://unicorns.com/#about*/
"photos/:id" : "getPhoto",
/*This is an example of using a ":param" variable which allows us to match
any of the components between two URL slashes*/
/*Sample usage: http://unicorns.com/#photos/5*/
"search/:query" : "searchPhotos",
/*We can also define multiple routes that are bound to the same map function,
in this case searchPhotos(). Note below how we're optionally passing in a
reference to a page number if one is supplied*/
/*Sample usage: http://unicorns.com/#search/lolcats*/
"search/:query/p:page" : "searchPhotos",
/*As we can see, URLs may contain as many ":param"s as we wish*/
/*Sample usage: http://unicorns.com/#search/lolcats/p1*/
"photos/:id/download/*imagePath" : "downloadPhoto",
/*This is an example of using a *splat. splats are able to match any number of
URL components and can be combined with ":param"s*/
/*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/
/*If you wish to use splats for anything beyond default routing, it's probably a good
idea to leave them at the end of a URL otherwise you may need to apply regular
expression parsing on your fragment*/
"*other" : "defaultRoute"
/*This is a default route that also uses a *splat. Consider the
default route a wildcard for URLs that are either not matched or where
the user has incorrectly typed in a route path manually*/
/*Sample usage: http://unicorns.com/#anything*/
},
showAbout: function(){
},
getPhoto: function(id){
/*
Note that the id matched in the above route will be passed to this function
*/
console.log("You are trying to reach photo " + id);
},
searchPhotos: function(query, page){
var page_number = page || 1;
console.log("Page number: " + page_number + " of the results for " + query);
},
downloadPhoto: function(id, path){
},
defaultRoute: function(other){
26 | Chapter 2: The Basics
console.log("Invalid. You attempted to reach:" + other);
}
});
/* Now that we have a router setup, remember to instantiate it*/
var myGalleryRouter = new GalleryRouter();
As of Backbone 0.5+, it’s possible to opt-in for HTML5 pushState support via win
dow.history.pushState. This permits you to define routes such as http://www.script-
junkie.com/just/an/example. This will be supported with automatic degradation when
a user’s browser doesn’t support pushState. For the purposes of this tutorial, we’ll use
the hashtag method.
Backbone.history
Next, we need to initialize Backbone.history as it handles hashchange events in our
application. This will automatically handle routes that have been defined and trigger
callbacks when they’ve been accessed.
The Backbone.history.start() method will simply tell Backbone that it’s OK to begin
monitoring all hashchange events as follows:
Backbone.history.start();
Router.navigate();
As an aside, if you would like to save application state to the URL at a particular point
you can use the .navigate() method to achieve this. It simply updates your URL frag-
ment without the need to trigger the hashchange event:
/*Lets imagine we would like a specific fragment for when a user zooms into a photo*/
zoomPhoto: function(factor){
this.zoom(factor); //imagine this zooms into the image
this.navigate("zoom/" + factor); //updates the fragment for us, but doesn't trigger the route
}
It is also possible for Router.navigate() to trigger the route as well as updating the URL
fragment.
zoomPhoto: function(factor){
this.zoom(factor); //imagine this zooms into the image
this.navigate("zoom/" + factor, true); //updates the fragment for us and triggers the route
}
Namespacing
When learning how to use Backbone, an important and commonly overlooked area by
tutorials is namespacing. If you already have experience with namespacing in Java-
Script, the following section will provide some advice on how to specifically apply
concepts you know to Backbone, however I will also be covering explanations for be-
ginners to ensure everyone is on the same page.
Namespacing | 27
What is namespacing?
The basic idea around namespacing is to avoid collisions with other objects or variables
in the global namespace. They’re important as it’s best to safeguard your code from
breaking in the event of another script on the page using the same variable names as
you are. As a good “citizen” of the global namespace, it’s also imperative that you do
your best to similarly not prevent other developer’s scripts executing due to the same
issues.
JavaScript doesn’t really have built-in support for namespaces like other languages,
however it does have closures which can be used to achieve a similar effect.
In this section we’ll be taking a look shortly at some examples of how you can name-
spaceyourmodels,views,routersandothercomponentsspecifically.Thepatternswe’ll
be examining are:
• Single global variables
• Object Literals
• Nested namespacing
Single global variables
One popular pattern for namespacing in JavaScript is opting for a single global variable
as your primary object of reference. A skeleton implementation of this where we return
an object with functions and properties can be found below:
var myApplication = (function(){
function(){
// ...
},
return {
// ...
}
})();
You’ve probably seen this technique before. A Backbone-specific example might look
like this:
var myViews = (function(){
return {
PhotoView: Backbone.View.extend({ .. }),
GalleryView: Backbone.View.extend({ .. }),
AboutView: Backbone.View.extend({ .. });
//etc.
};
})();
Here we can return a set of views, but the same technique could return an entire col-
lection of models, views and routers depending on how you decide to structure your
application. Although this works for certain situations, the biggest challenge with the
single global variable pattern is ensuring that no one else has used the same global
variable name as you have in the page.
28 | Chapter 2: The Basics
One solution to this problem, as mentioned by Peter Michaux, is to use prefix name-
spacing. It’s a simple concept at heart, but the idea is you select a common prefix name
(in this example, myApplication_) and then define any methods, variables or other ob-
jects after the prefix.
var myApplication_photoView = Backbone.View.extend({}),
myApplication_galleryView = Backbone.View.extend({});
This is effective from the perspective of trying to lower the chances of a particular
variable existing in the global scope, but remember that a uniquely named object can
have the same effect. This aside, the biggest issue with the pattern is that it can result
in a large number of global objects once your application starts to grow.
For more on Peter’s views about the single global variable pattern, read his excellent
post on them.
Note: There are several other variations on the single global variable pattern out in the
wild, however having reviewed quite a few, I felt the prefixing approach applied best
to Backbone.
Object Literals
Object Literals have the advantage of not polluting the global namespace but assist in
organizing code and parameters logically. They’re beneficial if you wish to create easily
readable structures that can be expanded to support deep nesting. Unlike simple global
variables, Object Literals often also take into account tests for the existence of a variable
by the same name, which helps reduce the chances of collision.
This example demonstrates two ways you can check to see if a namespace already exists
before defining it. I commonly use Option 2.
/*Doesn't check for existence of myApplication*/
var myApplication = {};
/*
Does check for existence. If already defined, we use that instance.
Option 1: if(!myApplication) myApplication = {};
Option 2: var myApplication = myApplication || {};
We can then populate our object literal to support models, views and collections (or any data, really):
*/
var myApplication = {
models : {},
views : {
pages : {}
},
collections : {}
};
One can also opt for adding properties directly to the namespace (such as your views,
in the following example):
Namespacing | 29
var myGalleryViews = myGalleryViews || {};
myGalleryViews.photoView = Backbone.View.extend({});
myGalleryViews.galleryView = Backbone.View.extend({});
The benefit of this pattern is that you’re able to easily encapsulate all of your models,
views, routers etc. in a way that clearly separates them and provides a solid foundation
for extending your code.
This pattern has a number of benefits. It’s often a good idea to decouple the default
configuration for your application into a single area that can be easily modified without
the need to search through your entire codebase just to alter it. Here’s an example of a
hypothetical object literal that stores application configuration settings:
var myConfig = {
language: 'english',
defaults: {
enableGeolocation: true,
enableSharing: false,
maxPhotos: 20
},
theme: {
skin: 'a',
toolbars: {
index: 'ui-navigation-toolbar',
pages: 'ui-custom-toolbar'
}
}
}
Note that there are really only minor syntactical differences between the Object Literal
pattern and a standard JSON data set. If for any reason you wish to use JSON for storing
your configurations instead (e.g. for simpler storage when sending to the back-end),
feel free to.
For more on the Object Literal pattern, I recommend reading Rebecca Murphey’s
excellent article on the topic.
Nested namespacing
An extension of the Object Literal pattern is nested namespacing. It’s another common
pattern used that offers a lower risk of collision due to the fact that even if a top-level
namespace already exists, it’s unlikely the same nested children do. For example, Ya-
hoo’s YUI uses the nested object namespacing pattern extensively:
YAHOO.util.Dom.getElementsByClassName('test');
Yahoo’s YUI uses the nested object namespacing pattern regularly and even Docu-
mentCloud(thecreatorsofBackbone)usethenestednamespacingpatternintheirmain
applications. A sample implementation of nested namespacing with Backbone may
look like this:
var galleryApp = galleryApp || {};
// perform similar check for nested children
30 | Chapter 2: The Basics
galleryApp.routers = galleryApp.routers || {};
galleryApp.model = galleryApp.model || {};
galleryApp.model.special = galleryApp.model.special || {};
// routers
galleryApp.routers.Workspace = Backbone.Router.extend({});
galleryApp.routers.PhotoSearch = Backbone.Router.extend({});
// models
galleryApp.model.Photo = Backbone.Model.extend({});
galleryApp.model.Comment = Backbone.Model.extend({});
// special models
galleryApp.model.special.Admin = Backbone.Model.extend({});
This is readable, clearly organized, and is a relatively safe way of namespacing your
Backbone application. The only real caveat however is that it requires your browser’s
JavaScript engine to first locate the galleryApp object, then dig down until it gets to the
function you’re calling. However, developers such as Juriy Zaytsev (kangax) have tested
and found the performance differences between single object namespacing vs the “nes-
ted” approach to be quite negligible.
Recommendation
Reviewing the namespace patterns above, the option that I prefer when writing Back-
bone applications is nested object namespacing with the object literal pattern.
Single global variables may work fine for applications that are relatively trivial. How-
ever, larger codebases requiring both namespaces and deep sub-namespaces require a
succinct solution that’s both readable and scalable. I feel this pattern achieves both of
these objectives and is a good choice for most Backbone development.
Additional Tips
Automated Backbone Scaffolding
Scaffolding can assist in expediting how quickly you can begin a new application by
creating the basic files required for a project automatically. If you enjoy the idea of
automated MVC scaffolding using Backbone, I’m happy to recommend checking out
a tool called Brunch.
It works very well with Backbone, Underscore, jQuery and CoffeeScript and is even
used by companies such as Red Bull and Jim Beam. You may have to update any third
party dependencies (e.g. latest jQuery or Zepto) when using it, but other than that it
should be fairly stable to use right out of the box.
Brunch can be installed via the nodejs package manager and is easy to get started with.
If you happen to use Vim or Textmate as your editor of choice, you’ll be happy to know
that there are Brunch bundles available for both.
Additional Tips | 31
Is there a limit to the number of routers I should be using?
Andrew de Andrade has pointed out that DocumentCloud themselves usually only use
a single router in most of their applications. You’re very likely to not require more than
one or two routers in your own projects as the majority of your application routing can
be kept organized in a single controller without it getting unwieldy.
Is Backbone too small for my application’s needs?
If you find yourself unsure of whether or not your application is too large to use Back-
bone, I recommend reading my post on building large-scale jQuery & JavaScript ap-
plications or reviewing my slides on client-side MVC architecture options. In both, I
cover alternative solutions and my thoughts on the suitability of current MVC solutions
for scaled application development.
Backbone can be used for building both trivial and complex applications as demon-
strated by the many examples Ashkenas has been referencing in the Backbone docu-
mentation. As with any MVC framework however, it’s important to dedicate time to-
wards planning out what models and views your application really needs. Diving
straight into development without doing this can result in either spaghetti code or a
large refactor later on and it’s best to avoid this where possible.
At the end of the day, the key to building large applications is not to build large appli-
cations in the first place. If you however find Backbone doesn’t cut it for your require-
ments I strongly recommend checking out JavaScriptMVC or SproutCore as these both
offer a little more than Backbone out of the box. Dojo and Dojo Mobile may also be of
interest as these have also been used to build significantly complex apps by other de-
velopers.
32 | Chapter 2: The Basics
CHAPTER 3
RESTful Applications
Building RESTful applications with Backbone
In this section of the book, we’re going to take a look at developing RESTful applica-
tions using Backbone.js and modern technology stacks. When the data for your back-
end is exposed through a purely RESTful API, tasks such as retrieving (GET), creating
(POST), updating (PUT) and deleting (DELETE) models are made easy through Back-
bone’s Model API. This API is so intuitive in fact that switching from storing records
in a local data-store (e.g localStorage) to a database/noSQL data-store is a lot simpler
than you may think.
Stack 1: Building A Backbone App With Node.js, Express,
Mongoose and MongoDB
The first stack we’ll be looking at is:
• Node.js
• Express
• Mongoose
• and MongoDB
with Jade used optionally as a view/templating engine.
Reviewing the stack
As you may know, node.js is an event-driven platform (built on the V8 runtime), de-
signed for writing fast, scalable network applications. It’s reasonably lightweight, effi-
cient and great for real-time applications that are data-intensive.
33
Express is a small web-development framework written with node.js, based on Sina-
tra. It supports a number of useful features such as intuitive views, robust routing and
a focus on high performance.
Next on the list are MongoDB and Mongoose. MongoDB is an open-source, document-
oriented database store designed with scalability and agility in mind. As a noSQL da-
tabase, rather than storing data in tables and rows (something we’re very used to doing
with relational databases), with MongoDB we instead store JSON-like documents us-
ing dynamic schemas. One of the goals of Mongo is to try bridging the gap between
key-value stores (speed, scalability) and relational databases (rich functionality).
Mongoose is a JavaScript library that simplifies how we interact with Mongo. Like
Express, it’s designed to work within the node.js environment and tries to solve some
of the complexities with asynchronous data storage by offering a more user-friendly
API. It also adds chaining features into the mix, allowing for a slightly more expressive
way of dealing with our data.
Jade is a template engine influenced by Haml (which we’ll be looking at later). It’s
implemented with JavaScript (and also runs under node). In addition to supporting
Express out of the box, it boasts a number of useful features including support for
mixins, includes, caching, template inheritance and much more. Whilst abstractions
like Jade certainly aren’t for everyone, our practical will cover working both with and
without it.
Practical
For this practical, we’re going to once again look at extending the popular Backbone
Todo application. Rather than relying on localStorage for data persistence, we’re going
to switch to storing Todos in a MongoDB document-store instead. The code for this
practical can be found in practicalsstacksoption2
app.js
(See here for the source)
We must first include the node dependencies required by our application. These are
Express, Mongoose and Path (a module containing utilities for dealing with file paths.
var application_root = __dirname,
express = require("express"),
path = require("path"),
mongoose = require('mongoose');
Next, create a new Express server. express.createServer() is a simple way of creating
an instance of express.HTTPServer, which we’ll be using to pass in our routes.
var app = express.createServer();
After this, connect Mongoose up to a database (in our case, localhost should suffice).
Should you require the ability to pass in authentication information, here’s a sample
34 | Chapter 3: RESTful Applications
containing all of the supported URL parameters: mongodb://[username:pass
word@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
mongoose.connect('mongodb://localhost/my_database');
A Mongoose model for any Todo item can now be easily defined by passing a schema
instance to mongoose.model. In our case the schema covers a Todo item’s text content,
its done state and order position in the overall Todo list.
var Todo = mongoose.model('Todo', new mongoose.Schema({
text: String,
done: Boolean,
order: Number
}));
The configure() methods allows us to setup what we need for the current environment
with our Express server. Note that lower down in the configuration are two view/view
related lines. The last one explicitly sets the viewing/templating engine to be used as
Jade app.set('view engine', 'jade'). We can avoid these if we wish to use plain
HTML/JS for our templates instead.
app.configure(function(){
// the bodyParser middleware parses JSON request bodies
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.set('views', path.join(application_root, "views"));
app.set('view engine', 'jade')
});
Should you prefer to switch out Jade for an alternative view engine, this can be done
fairly trivially. See the section under “Templating” here: https://github.com/joyent/
node/wiki/modules. For example, to switch to EJS, you would simply write
app.set('view engine', 'ejs')
Express makes use of common HTTP verbs (get, put, post etc.) to provide easy to use,
expressive routing API based on CRUD (Create, Read, Update and Delete). Below for
example, we can define what happens when the browser requests the root “/”. As a
trivial route in this application, it doesn’t do anything particularly exciting, however
getters typically read or retrieve data.
app.get('/', function(req, res){
res.send('Hello World');
});
Onto something a little more useful and in our next route, navigating to “/todo” will
actually render our Jade view “todo.jade”, as seen in the callback. Additional config-
uration values can be passed as the second parameter, such as the custom title specified
below.
Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB | 35
app.get('/todo', function(req, res){
res.render('todo', {title: "Our sample application"});
});
Next, we can see the first of our “/api/” routes.
app.get('/api/todos', function(req, res){
return Todo.find(function(err, todos) {
return res.send(todos);
});
});
The callback to our next route supports querying for todos based on a specific ID. The
route string itself (once compiled) will be converted from “/api/todos/:id” to a regular
expression. As you might have guessed, this is a hint that routes can also be regular
expression literals if we wished to do something more complex.
app.get('/api/todos/:id', function(req, res){
return Todo.findById(req.params.id, function(err, todo) {
if (!err) {
return res.send(todo);
}
});
});
Similarly, we want to support updating todos based on a specific ID as well. The fol-
lowing allows us to query a todo by ID and then update the values of it’s three attributes
(text, done, order) easily.
app.put('/api/todos/:id', function(req, res){
return Todo.findById(req.params.id, function(err, todo) {
todo.text = req.body.text;
todo.done = req.body.done;
todo.order = req.body.order;
return todo.save(function(err) {
if (!err) {
console.log("updated");
}
return res.send(todo);
});
});
});
We’ve so far covered requesting todos and updating them, but a core part of the ap-
plication requires us to insert (or add) new todos to our data-store. Below we can create
new Todo models and simply save them.
app.post('/api/todos', function(req, res){
var todo;
todo = new Todo({
text: req.body.text,
done: req.body.done,
order: req.body.order
});
todo.save(function(err) {
if (!err) {
36 | Chapter 3: RESTful Applications
Another Random Scribd Document
with Unrelated Content
leading division, so as to be ready for battle. Sitting on his horse by
the road-side, while the deployment was making, he saw a man
coming down the road, riding as hard as he could, and as he
approached he recognized him as one of his own "foragers,"
mounted on a white horse, with a rope bridle and a blanket for
saddle. As he came near he called out, "Hurry up, general; we have
got the railroad!" So, while we, the generals, were proceeding
deliberately to prepare for a serious battle, a parcel of our foragers,
in search of plunder, had got ahead and actually captured the South
Carolina Railroad, a line of vital importance to the rebel Government.
As soon as we struck the railroad, details of men were set to work
to tear up the rails, to burn the ties and twist the bars. This was a
most important railroad, and I proposed to destroy it completely for
fifty miles, partly to prevent a possibility of its restoration and partly
to utilize the time necessary for General Slocum to get up.
The country thereabouts was very poor, but the inhabitants mostly
remained at home. Indeed, they knew not where to go. The enemy's
cavalry had retreated before us, but his infantry was reported in
some strength at Branchville, on the farther side of the Edisto; yet
on the appearance of a mere squad of our men they burned their
own bridges the very thing I wanted, for we had no use for them,
and they had.
We all remained strung along this railroad till the 9th of February--
the Seventeenth Corps on the right, then the Fifteenth, Twentieth,
and cavalry, at Blackville. General Slocum reached Blackville that
day, with Geary's division of the Twentieth Corps, and reported the
Fourteenth Corps (General Jeff. C. Davis's) to be following by way of
Barnwell. On the 10th I rode up to Blackville, where I conferred with
Generals Slocum and Kilpatrick, became satisfied that the whole
army would be ready within a day, and accordingly made orders for
the next movement north to Columbia, the right wing to strike
Orangeburg en route. Kilpatrick was ordered to demonstrate strongly
toward Aiken, to keep up the delusion that we might turn to
Augusta; but he was notified that Columbia was the next objective,
and that he should cover the left flank against Wheeler, who hung
around it. I wanted to reach Columbia before any part of Hood's
army could possibly get there. Some of them were reported as
having reached Augusta, under the command of General Dick Taylor.
Having sufficiently damaged the railroad, and effected the junction
of the entire army, the general march was resumed on the 11th,
each corps crossing the South Edisto by separate bridges, with
orders to pause on the road leading from Orangeberg to Augusta, till
it was certain that the Seventeenth Corps had got possession of
Orangeburg. This place was simply important as its occupation
would sever the communications between Charleston and Columbia.
All the heads of column reached this road, known as the Edgefield
road, during the 12th, and the Seventeenth Corps turned to the
right, against Orangeburg. When I reached the head of column
opposite Orangeburg, I found Giles A. Smith's division halted, with a
battery unlimbered, exchanging shots with a party on the opposite
side of the Edisto. He reported that the bridge was gone, and that
the river was deep and impassable. I then directed General Blair to
send a strong division below the town, some four or five miles, to
effect a crossing there. He laid his pontoon-bridge, but the bottom
on the other side was overflowed, and the men had to wade through
it, in places as deep as their waists. I was with this division at the
time, on foot, trying to pick my way across the overflowed bottom;
but, as soon as the head of column reached the sand-hills, I knew
that the enemy would not long remain in Orangeburg, and
accordingly returned to my horse, on the west bank, and rode
rapidly up to where I had left Giles A. Smith. I found him in
possession of the broken bridge, abreast of the town, which he was
repairing, and I was among the first to cross over and enter the
town. By and before the time either Force's or Giles A. Smith's
skirmishers entered the place, several stores were on fire, and I am
sure that some of the towns-people told me that a Jew merchant
had set fire to his own cotton and store, and from this the fire had
spread. This, however, was soon put out, and the Seventeenth Corps
(General Blair) occupied the place during that night. I remember to
have visited a large hospital, on the hill near the railroad depot,
which was occupied by the orphan children who had been removed
from the asylum in Charleston. We gave them protection, and, I
think, some provisions. The railroad and depot were destroyed by
order, and no doubt a good deal of cotton was burned, for we all
regarded cotton as hostile property, a thing to be destroyed. General
Blair was ordered to break up this railroad, forward to the point
where it crossed the Santee, and then to turn for Columbia. On the
morning of the 13th I again joined the Fifteenth Corps, which
crossed the North Edisto by Snilling's Bridge, and moved straight for
Columbia, around the head of Caw-Caw Swamp. Orders were sent to
all the columns to turn for Columbia, where it was supposed the
enemy had concentrated all the men they could from Charleston,
Augusta, and even from Virginia. That night I was with the Fifteenth
Corps, twenty-one miles from Columbia, where my aide, Colonel
Audenried, picked up a rebel officer on the road, who, supposing
him to be of the same service with himself, answered all his
questions frankly, and revealed the truth that there was nothing in
Columbia except Hampton's cavalry. The fact was, that General
Hardee, in Charleston, took it for granted that we were after
Charleston; the rebel troops in Augusta supposed they were "our
objective;" so they abandoned poor Columbia to the care of
Hampton's cavalry, which was confused by the rumors that poured in
on it, so that both Beauregard and Wade Hampton, who were in
Columbia, seem to have lost their heads.
On the 14th the head of the Fifteenth Corps, Charles R. Woods's
division, approached the Little Congaree, a broad, deep stream,
tributary to the Main Congaree; six or eight miles below Columbia.
On the opposite side of this stream was a newly-constructed fort,
and on our side--a wide extent of old cotton-fields, which, had been
overflowed, and was covered with a deep slime. General Woods had
deployed his leading brigade, which was skirmishing forward, but he
reported that the bridge was gone, and that a considerable force of
the enemy was on the other side. I directed General Howard or
Logan to send a brigade by a circuit to the left, to see if this stream
could not be crossed higher up, but at the same time knew that
General Slocum's route world bring him to Colombia behind this
stream, and that his approach would uncover it. Therefore, there
was no need of exposing much life. The brigade, however, found
means to cross the Little Congaree, and thus uncovered the passage
by the main road, so that General Woods's skirmishers at once
passed over, and a party was set to work to repair the bridge, which
occupied less than an hour, when I passed over with my whole staff.
I found the new fort unfinished and unoccupied, but from its parapet
could see over some old fields bounded to the north and west by
hills skirted with timber. There was a plantation to our left, about
half a mile, and on the edge of the timber was drawn up a force of
rebel cavalry of about a regiment, which advanced, and charged
upon some, of our foragers, who were plundering the plantation; my
aide, Colonel Audenried, who had ridden forward, came back
somewhat hurt and bruised, for, observing this charge of cavalry, he
had turned for us, and his horse fell with him in attempting to leap a
ditch. General Woods's skirmish-line met this charge of cavalry, and
drove it back into the woods and beyond. We remained on that
ground during the night of the 15th, and I camped on the nearest
dry ground behind the Little Congaree, where on the next morning
were made the written' orders for the government of the troops
while occupying Columbia. These are dated February 16, 1865, in
these words:
General Howard will cross the Saluda and Broad Rivers as near
their mouths as possible, occupy Columbia, destroy the public
buildings, railroad property, manufacturing and machine shops; but
will spare libraries, asylums, and private dwellings. He will then
move to Winnsboro', destroying en route utterly that section of the
railroad. He will also cause all bridges, trestles, water-tanks, and
depots on the railroad back to the Wateree to be burned, switches
broken, and such other destruction as he can find time to
accomplish consistent with proper celerity.
These instructions were embraced in General Order No. 26, which
prescribed the routes of march for the several columns as far as
Fayetteville, North Carolina, and is conclusive that I then regarded
Columbia as simply one point on our general route of march, and
not as an important conquest.
During the 16th of February the Fifteenth Corps reached the point
opposite Columbia, and pushed on for the Saluda Factory three miles
above, crossed that stream, and the head of column reached Broad
River just in time to find its bridge in flames, Butler's cavalry having
just passed over into Columbia. The head of Slocum's column also
reached the point opposite Columbia the same morning, but the bulk
of his army was back at Lexington. I reached this place early in the
morning of the 16th, met General Slocum there; and explained to
him the purport of General Order No. 26, which contemplated the
passage of his army across Broad River at Alston, fifteen miles above
Columbia. Riding down to the river-bank, I saw the wreck of the
large bridge which had been burned by the enemy, with its many
stone piers still standing, but the superstructure gone. Across the
Congaree River lay the city of Columbia, in plain, easy view. I could
see the unfinished State-House, a handsome granite structure, and
the ruins of the railroad depot, which were still smouldering.
Occasionally a few citizens or cavalry could be seen running across
the streets, and quite a number of negroes were seemingly busy in
carrying off bags of grain or meal, which were piled up near the
burned depot.
Captain De Gres had a section of his twenty-pound Parrott guns
unlimbered, firing into the town. I asked him what he was firing for;
he said he could see some rebel cavalry occasionally at the
intersections of the streets, and he had an idea that there was a
large force of infantry concealed on the opposite bank, lying low, in
case we should attempt to cross over directly into the town. I
instructed him not to fire any more into the town, but consented to
his bursting a few shells near the depot, to scare away the negroes
who were appropriating the bags of corn and meal which we
wanted, also to fire three shots at the unoccupied State-House. I
stood by and saw these fired, and then all firing ceased. Although
this matter of firing into Columbia has been the subject of much
abuse and investigation, I have yet to hear of any single person
having been killed in Columbia by our cannon. On the other hand,
the night before, when Woods's division was in camp in the open
fields at Little Congaree, it was shelled all night by a rebel battery
from the other aide of the river. This provoked me much at the time,
for it was wanton mischief, as Generals Beauregard and Hampton
must have been convinced that they could not prevent our entrance
into Columbia. I have always contended that I would have been
justified in retaliating for this unnecessary act of war, but did not,
though I always characterized it as it deserved.
The night of the 16th I camped near an old prison bivouac
opposite Columbia, known to our prisoners of war as "Camp
Sorghum," where remained the mud-hovels and holes in the ground
which our prisoners had made to shelter themselves from the
winter's cold and the summer's heat. The Fifteenth Corps was then
ahead, reaching to Broad River, about four miles above Columbia;
the Seventeenth Corps was behind, on the river-bank opposite
Columbia; and the left wing and cavalry had turned north toward
Alston.
The next morning, viz., February 17th, I rode to the head of
General Howard's column, and found that during the night he had
ferried Stone's brigade of Woods's division of the Fifteenth Corps
across by rafts made of the pontoons, and that brigade was then
deployed on the opposite bank to cover the construction of a
pontoon-bridge nearly finished.
I sat with General Howard on a log, watching the men lay this
bridge; and about 9 or 10 A.M. a messenger came from Colonel
Stone on the other aide, saying that the Mayor of Columbia had
come out of the city to surrender the place, and asking for orders. I
simply remarked to General Howard that he had his orders, to let
Colonel Stone go on into the city, and that we would follow as soon
as the bridge was ready. By this same messenger I received a note
in pencil from the Lady Superioress of a convent or school in
Columbia, in which she claimed to have been a teacher in a convent
in Brown County, Ohio, at the time my daughter Minnie was a pupil
there, and therefore asking special protection. My recollection is,
that I gave the note to my brother-in-law, Colonel Ewing, then
inspector-general on my staff, with instructions to see this lady, and
assure her that we contemplated no destruction of any private
property in Columbia at all.
As soon as the bridge was done, I led my horse over it, followed
by my whole staff. General Howard accompanied me with his, and
General Logan was next in order, followed by General C. R. Woods,
and the whole of the Fifteenth Corps. Ascending the hill, we soon
emerged into a broad road leading into Columbia, between old fields
of corn and cotton, and, entering the city, we found seemingly all its
population, white and black, in the streets. A high and boisterous
wind was prevailing from the north, and flakes of cotton were flying
about in the air and lodging in the limbs of the trees, reminding us
of a Northern snow-storm. Near the market-square we found Stone's
brigade halted, with arms stacked, and a large detail of his men,
along with some citizens, engaged with an old fire-engine, trying to
put out the fire in a long pile of burning cotton-bales, which I was
told had been fired by the rebel cavalry on withdrawing from the city
that morning. I know that, to avoid this row of burning cotton-bales,
I had to ride my horse on the sidewalk. In the market-square had
collected a large crowd of whites and blacks, among whom was the
mayor of the city, Dr. Goodwin, quite a respectable old gentleman,
who was extremely anxious to protect the interests of the citizens.
He was on foot, and I on horseback, and it is probable I told him
then not to be uneasy, that we did not intend to stay long, and had
no purpose to injure the private citizens or private property. About
this time I noticed several men trying to get through the crowd to
speak with me, and called to some black people to make room for
them; when they reached me, they explained that they were officers
of our army, who had been prisoners, had escaped from the rebel
prison and guard, and were of course overjoyed to find themselves
safe with us. I told them that, as soon as things settled down, they
should report to General Howard, who would provide for their safety,
and enable them to travel with us. One of them handed me a paper,
asking me to read it at my leisure; I put it in my breast-pocket and
rode on. General Howard was still with me, and, riding down the
street which led by the right to the Charleston depot, we found it
and a large storehouse burned to the ground, but there were, on the
platform and ground near by, piles of cotton bags filled with corn
and corn-meal, partially burned.
A detachment of Stone's brigade was guarding this, and
separating the good from the bad. We rode along the railroad-track,
some three or four hundred yards, to a large foundery, when some
man rode up and said the rebel cavalry were close by, and he
warned us that we might get shot. We accordingly turned back to
the market-square, and en route noticed that, several of the men
were evidently in liquor, when I called General Howard's attention to
it. He left me and rode toward General Woods's head of column,
which was defiling through the town. On reaching the market-
square, I again met Dr. Goodwin, and inquired where he proposed to
quarter me, and he said that he had selected the house of Blanton
Duncan, Esq., a citizen of Louisville, Kentucky, then a resident there,
who had the contract for manufacturing the Confederate money, and
had fled with Hampton's cavalry. We all rode some six or eight
squares back from the new State-House, and found a very good
modern house, completely furnished, with stabling and a large yard,
took it as our headquarters, and occupied it during our stay. I
considered General Howard as in command of the place, and
referred the many applicants for guards and protection to him.
Before our headquarters-wagons had got up, I strolled through the
streets of Columbia, found sentinels posted at the principal
intersections, and generally good order prevailing, but did not again
return to the main street, because it was filled with a crowd of
citizens watching the soldiers marching by.
During the afternoon of that day, February 17th, the whole of the
Fifteenth Corps passed through the town and out on the Camden
and Winnsboro' roads. The Seventeenth Corps did not enter the city
at all, but crossed directly over to the Winnsboro' road from the
pontoon bridge at Broad River, which was about four miles above the
city.
After we had got, as it were, settled in Blanton Duncan's house,
say about 2 p.m., I overhauled my pocket according to custom, to
read more carefully the various notes and memoranda received
during the day, and found the paper which had been given me, as
described, by one of our escaped prisoners. It proved to be the song
of "Sherman's March to the Sea," which had been composed by
Adjutant S. H. M. Byers, of the Fifth Iowa Infantry, when a prisoner
in the asylum at Columbia, which had been beautifully written off by
a fellow-prisoner, and handed to me in person. This appeared to me
so good that I at once sent for Byers, attached him to my staff,
provided him with horse and equipment, and took him as far as
Fayetteville, North Carolina, whence he was sent to Washington as
bearer of dispatches. He is now United States consul at Zurich,
Switzerland, where I have since been his guest. I insert the song
here for convenient reference and preservation. Byers said that there
was an excellent glee-club among the prisoners in Columbia, who
used to sing it well, with an audience often of rebel ladies:
SHERMAN'S MARCH TO THE SEA.
Composed by Adjutant Byers, Fifth Iowa Infantry. Arranged and
sung by the Prisoners in Columbia Prison.
I
Our camp-fires shone bright on the mountain
That frowned on the river below,
As we stood by our guns in the morning,
And eagerly watched for the foe;
When a rider came out of the darkness
That hung over mountain and tree,
And shouted, "Boys, up and be ready!
For Sherman will march to the sea!"
CHORUS:
Then sang we a song of our chieftain,
That echoed over river and lea;
And the stars of our banner shone brighter
When Sherman marched down to the sea!
II
Then cheer upon cheer for bold Sherman
Went up from each valley and glen,
And the bugles reechoed the music
That came from the lips of the men;
For we knew that the stars in our banner
More bright in their splendor would be,
And that blessings from Northland world greet us,
When Sherman marched down to the sea!
Then sang we a song, etc.
III
Then forward, boys! forward to battle!
We marched on our wearisome way,
We stormed the wild hills of Resacar
God bless those who fell on that day!
Then Kenesaw frowned in its glory,
Frowned down on the flag of the free;
But the East and the West bore our standard,
And Sherman marched on to the sea!
Then sang we a song, etc.
IV
Still onward we pressed, till our banners
Swept out from Atlanta's grim walls,
And the blood of the patriot dampened
The soil where the traitor-flag falls;
But we paused not to weep for the fallen,
Who slept by each river and tree,
Yet we twined them a wreath of the laurel,
As Sherman marched down to the sea!
Then sang we a song, etc.
V
Oh, proud was our army that morning,
That stood where the pine darkly towers,
When Sherman said, "Boys, you are weary,
But to-day fair Savannah is ours!"
Then sang we the song of our chieftain,
That echoed over river and lea,
And the stars in our banner shone brighter
When Sherman camped down by the sea!
Toward evening of February 17th, the mayor, Dr. Goodwin, came
to my quarters at Duncan's house, and remarked that there was a
lady in Columbia who professed to be a special friend of mine. On
his giving her name, I could not recall it, but inquired as to her
maiden or family name. He answered Poyas. It so happened that,
when I was a lieutenant at Fort Moultrie, in 1842-'46, I used very
often to visit a family of that name on the east branch of Cooper
River, about forty miles from Fort Moultrie, and to hunt with the son,
Mr. James Poyas, an elegant young fellow and a fine sportsman. His
father, mother, and several sisters, composed the family, and were
extremely hospitable. One of the ladies was very fond of painting in
water-colors, which was one of my weaknesses, and on one
occasion I had presented her with a volume treating of water-colors.
Of course, I was glad to renew the acquaintance, and proposed to
Dr. Goodwin that we should walk to her house and visit this lady,
which we did. The house stood beyond the Charlotte depot, in a
large lot, was of frame, with a high porch, which was reached by a
set of steps outside. Entering this yard, I noticed ducks and
chickens, and a general air of peace and comfort that was really
pleasant to behold at that time of universal desolation; the lady in
question met us at the head of the steps and invited us into a parlor
which was perfectly neat and well furnished. After inquiring about
her father, mother, sisters, and especially her brother James, my
special friend, I could not help saying that I was pleased to notice
that our men had not handled her house and premises as roughly as
was their wont. "I owe it to you, general," she answered. "Not at all.
I did not know you were here till a few minutes ago." She reiterated
that she was indebted to me for the perfect safety of her house and
property, and added, "You remember, when you were at our house
on Cooper River in 1845, you gave me a book;" and she handed me
the book in question, on the fly leaf of which was written: "To Miss
Poyas, with the compliments of W. T. Sherman, First-lieutenant Third
Artillery." She then explained that, as our army approached
Columbia, there was a doubt in her mind whether the terrible
Sherman who was devastating the land were W. T. Sherman or T. W.
Sherman, both known to be generals in the Northern army; but, on
the supposition that he was her old acquaintance, when Wade
Hampton's cavalry drew out of the city, calling out that the Yankees
were coming, she armed herself with this book, and awaited the
crisis. Soon the shouts about the markethouse announced that the
Yankees had come; very soon men were seen running up and down
the streets; a parcel of them poured over the fence, began to chase
the chickens and ducks, and to enter her house. She observed one
large man, with full beard, who exercised some authority, and to him
she appealed in the name of "his general." "What do you know of
Uncle Billy?" "Why," she said, "when he was a young man he used to
be our friend in Charleston, and here is a book he gave me." The
officer or soldier took the book, looked at the inscription, and,
turning to his fellows, said: "Boys, that's so; that's Uncle Billy's
writing, for I have seen it often before." He at once commanded the
party to stop pillaging, and left a man in charge of the house, to
protect her until the regular provost-guard should be established. I
then asked her if the regular guard or sentinel had been as good to
her. She assured me that he was a very nice young man; that he
had been telling her all about his family in Iowa; and that at that
very instant of time he was in another room minding her baby. Now,
this lady had good sense and tact, and had thus turned aside a party
who, in five minutes more, would have rifled her premises of all that
was good to eat or wear. I made her a long social visit, and, before
leaving Columbia, gave her a half-tierce of rice and about one
hundred pounds of ham from our own mess-stores.
In like manner, that same evening I found in Mrs. Simons another
acquaintance--the wife of the brother of Hon. James Simons, of
Charleston, who had been Miss Wragg. When Columbia was on fire
that night, and her house in danger, I had her family and effects
carried to my own headquarters, gave them my own room and bed,
and, on leaving Columbia the next day, supplied her with a half-
barrel of hams and a half-tierce of rice. I mention these specific facts
to show that, personally, I had no malice or desire to destroy that
city or its inhabitants, as is generally believed at the South.
Having walked over much of the suburbs of Columbia in the
afternoon, and being tired, I lay down on a bed in Blanton Duncan's
house to rest. Soon after dark I became conscious that a bright light
was shining on the walls; and, calling some one of my staff (Major
Nichols, I think) to inquire the cause, he said there seemed to be a
house on fire down about the market-house. The same high wind
still prevailed, and, fearing the consequences, I bade him go in
person to see if the provost-guard were doing its duty. He soon
returned, and reported that the block of buildings directly opposite
the burning cotton of that morning was on fire, and that it was
spreading; but he had found General Woods on the ground, with
plenty of men trying to put the fire out, or, at least, to prevent its
extension. The fire continued to increase, and the whole heavens
became lurid. I dispatched messenger after messenger to Generals
Howard, Logan, and Woods, and received from them repeated
assurances that all was being done that could be done, but that the
high wind was spreading the flames beyond all control. These
general officers were on the ground all night, and Hazen's division
had been brought into the city to assist Woods's division, already
there. About eleven o'clock at night I went down-town myself,
Colonel Dayton with me; we walked to Mr. Simons's house, from
which I could see the flames rising high in the air, and could hear
the roaring of the fire. I advised the ladies to move to my
headquarters, had our own headquarter-wagons hitched up, and
their effects carried there, as a place of greater safety. The whole air
was full of sparks and of flying masses of cotton, shingles, etc.,
some of which were carried four or five blocks, and started new
fires. The men seemed generally under good control, and certainly
labored hard to girdle the fire, to prevent its spreading; but, so long
as the high wind prevailed, it was simply beyond human possibility.
Fortunately, about 3 or 4 a.m., the wind moderated, and gradually
the fire was got under control; but it had burned out the very heart
of the city, embracing several churches, the old State-House, and the
school or asylum of that very Sister of Charity who had appealed for
my personal protection. Nickerson's Hotel, in which several of my
staff were quartered, was burned down, but the houses occupied by
myself, Generals Howard and Logan, were not burned at all. Many of
the people thought that this fire was deliberately planned and
executed. This is not true. It was accidental, and in my judgment
began with the cotton which General Hampton's men had set fire to
on leaving the city (whether by his orders or not is not material),
which fire was partially subdued early in the day by our men; but,
when night came, the high wind fanned it again into full blaze,
carried it against the frame houses, which caught like tinder, and
soon spread beyond our control.
This whole subject has since been thoroughly and judicially
investigated, in some cotton cases, by the mixed commission on
American and British claims, under the Treaty of Washington, which
commission failed to award a verdict in favor of the English
claimants, and thereby settled the fact that the destruction of
property in Columbia, during that night, did not result from the acts
of the General Government of the United States--that is to say, from
my army. In my official report of this conflagration, I distinctly
charged it to General Wade Hampton, and confess I did so pointedly,
to shake the faith of his people in him, for he was in my opinion
boastful, and professed to be the special champion of South
Carolina.
Full Size
The morning sun of February 18th rose bright and clear over a
ruined city. About half of it was in ashes and in smouldering heaps.
Many of the people were houseless, and gathered in groups in the
suburbs, or in the open parks and spaces, around their scanty piles
of furniture. General Howard, in concert with the mayor, did all that
was possible to provide other houses for them; and by my authority
he turned over to the Sisters of Charity the Methodist College, and to
the mayor five hundred beef-cattle; to help feed the people; I also
gave the mayor (Dr. Goodwin) one hundred muskets, with which to
arm a guard to maintain order after we should leave the
neighborhood. During the 18th and 19th we remained in Columbia,
General Howard's troops engaged in tearing up and destroying the
railroad, back toward the Wateree, while a strong detail, under the
immediate supervision of Colonel O. M. Poe, United States
Engineers, destroyed the State Arsenal, which was found to be well
supplied with shot, shell, and ammunition. These were hauled in
wagons to the Saluda River, under the supervision of Colonel Baylor,
chief of ordnance, and emptied into deep water, causing a very
serious accident by the bursting of a percussion-shell, as it struck
another on the margin of the water. The flame followed back a train
of powder which had sifted out, reached the wagons, still partially
loaded, and exploded them, killing sixteen men and destroying
several wagons and teams of mules. We also destroyed several
valuable founderies and the factory of Confederate money. The dies
had been carried away, but about sixty handpresses remained. There
was also found an immense quantity of money, in various stages of
manufacture, which our men spent and gambled with in the most
lavish manner.
Having utterly ruined Columbia, the right wing began its march
northward, toward Winnsboro', on the 20th, which we reached on
the 21st, and found General Slocum, with the left wing, who had
come by the way of Alston. Thence the right wing was turned
eastward, toward Cheraw, and Fayetteville, North Carolina, to cross
the Catawba River at Peay's Ferry. The cavalry was ordered to follow
the railroad north as far as Chester, and then to turn east to Rocky
Mount, the point indicated for the passage of the left wing. In
person I reached Rocky Mount on the 22d, with the Twentieth Corps,
which laid its pontoon-bridge and crossed over during the 23d.
Kilpatrick arrived the next day, in the midst of heavy rain, and was
instructed to cross the Catawba at once, by night, and to move up to
Lancaster, to make believe we were bound for Charlotte, to which
point I heard that Beauregard had directed all his detachments,
including a corps of Hood's old army, which had been marching
parallel with us, but had failed to make junction with, the forces
immediately opposing us. Of course, I had no purpose of going to
Charlotte, for the right wing was already moving rapidly toward
Fayetteville, North Carolina. The rain was so heavy and persistent
that the Catawba, River rose fast, and soon after I had crossed the
pontoon bridge at Rocky Mount it was carried away, leaving General
Davis, with the Fourteenth Corps, on the west bank. The roads were
infamous, so I halted the Twentieth Corps at Hanging Rock for some
days, to allow time for the Fourteenth to get over.
General Davis had infinite difficulty in reconstructing his bridge,
and was compelled to use the fifth chains of his wagons for anchor-
chains, so that we were delayed nearly a week in that neighborhood.
While in camp at Hanging Rock two prisoners were brought to me--
one a chaplain, the other a boy, son of Richard Bacot, of Charleston,
whom I had known as a cadet at West Point. They were just from
Charleston, and had been sent away by General Hardee in advance,
because he was, they said, evacuating Charleston. Rumors to the
same effect had reached me through the negroes, and it was,
moreover, reported that Wilmington, North Carolina, was in
possession of the Yankee troops; so that I had every reason to be
satisfied that our march was fully reaping all the fruits we could
possibly ask for. Charleston was, in fact, evacuated by General
Hardee on the 18th of February, and was taken possession of by a
brigade of General Fosters troops, commanded by General
Schimmelpfennig, the same day. Hardee had availed himself of his
only remaining railroad, by Florence to Cheraw; had sent there much
of his ammunition and stores, and reached it with the effective part
of the garrison in time to escape across the Pedee River before our
arrival. Wilmington was captured by General Terry on the 22d of
February; but of this important event we only knew by the vague
rumors which reached us through rebel sources.
General Jeff. C. Davis got across the Catawba during the 27th, and
the general march was resumed on Cheraw. Kilpatrick remained near
Lancaster, skirmishing with Wheeler's and Hampton's cavalry,
keeping up the delusion that we proposed to move on Charlotte and
Salisbury, but with orders to watch the progress of the Fourteenth
Corps, and to act in concert with it, on its left rear. On the 1st of
March I was at Finlay's Bridge across Lynch's Creek, the roads so
bad that we had to corduroy nearly every foot of the way; but I was
in communication with all parts of the army, which had met no
serious opposition from the enemy. On the 2d of March we entered
the village of Chesterfield, skirmishing with Butler's cavalry, which
gave ground rapidly. There I received a message from General
Howard, who, reported that he was already in Cheraw with the
Seventeenth Corps, and that the Fifteenth was near at hand.
General Hardee had retreated eastward across the Pedee, burning
the bridge. I therefore directed the left wing to march for
Sneedsboro', about ten miles above Cheraw, to cross the Pedee
there, while I in person proposed to cross over and join the right
wing in Cheraw. Early in the morning of the 3d of March I rode out
of Chesterfield along with the Twentieth Corps, which filled the road,
forded Thompson's Creek, and, at the top of the hill beyond, found a
road branching off to the right, which corresponded with the one, on
my map leading to Cheraw. Seeing a negro standing by the
roadside, looking at the troops passing, I inquired of him what road
that was. "Him lead to Cheraw, master!" "Is it a good road, and how
far?" "A very good road, and eight or ten miles." "Any guerrillas?"
"Oh! no, master, dey is gone two days ago; you could have played
cards on der coat-tails, dey was in sich a hurry!" I was on my
Lexington horse, who was very handsome and restive, so I made
signal to my staff to follow, as I proposed to go without escort. I
turned my horse down the road, and the rest of the staff followed.
General Barry took up the questions about the road, and asked the
same negro what he was doing there. He answered, "Dey say Massa
Sherman will be along soon!" "Why," said General Barry, "that was
General Sherman you were talking to." The poor negro, almost in
the attitude of prayer, exclaimed: "De great God! just look at his
horse!" He ran up and trotted by my side for a mile or so, and gave
me all the information he possessed, but he seemed to admire the
horse more than the rider.
We reached Cheraw in a couple of hours in a drizzling rain, and,
while waiting for our wagons to come up, I staid with General Blair
in a large house, the property of a blockade-runner, whose family
remained. General Howard occupied another house farther down-
town. He had already ordered his pontoon-bridge to be laid across
the Pedee, there a large, deep, navigable stream, and Mower's
division was already across, skirmishing with the enemy about two
miles out. Cheraw was found to be full of stores which had been
sent up from Charleston prior to its evacuation, and which could not
be removed. I was satisfied, from inquiries, that General Hardee had
with him only the Charleston garrison, that the enemy had not
divined our movements, and that consequently they were still
scattered from Charlotte around to Florence, then behind us. Having
thus secured the passage of the Pedee, I felt no uneasiness about
the future, because there remained no further great impediment
between us and Cape Fear River, which I felt assured was by that
time in possession of our friends. The day was so wet that we all
kept in-doors; and about noon General Blair invited us to take lunch
with him. We passed down into the basement dining-room, where
the regular family table was spread with an excellent meal; and
during its progress I was asked to take some wine, which stood
upon the table in venerable bottles. It was so very good that I
inquired where it came from. General Blair simply asked, "Do you
like it?" but I insisted upon knowing where he had got it; he only
replied by asking if I liked it, and wanted some. He afterward sent to
my bivouac a case containing a dozen bottles of the finest madeira I
ever tasted; and I learned that he had captured, in Cheraw, the wine
of some of the old aristocratic families of Charleston, who had sent it
up to Cheraw for safety, and heard afterward that Blair had found
about eight wagon-loads of this wine, which he distributed to the
army generally, in very fair proportions.
After finishing our lunch, as we passed out of the dining room,
General Blair asked me, if I did not want some saddle-blankets, or a
rug for my tent, and, leading me into the hall to a space under the
stairway, he pointed out a pile of carpets which had also been sent
up from Charleston for safety. After our headquarter-wagons got up,
and our bivouac was established in a field near by, I sent my orderly
(Walter) over to General Blair, and he came back staggering under a
load of carpets, out of which the officers and escort made excellent
tent-rugs, saddle-cloths, and blankets. There was an immense
amount of stores in Cheraw, which were used or destroyed; among
them twenty-four guns, two thousand muskets, and thirty-six
hundred barrels of gunpowder. By the carelessness of a soldier, an
immense pile of this powder was exploded, which shook the town
badly; and killed and maimed several of our men.
We remained in or near Cheraw till the 6th of March, by which
time the army was mostly across the Pedee River, and was prepared
to resume the march on Fayetteville. In a house where General
Hardee had been, I found a late New York Tribune, of fully a month
later date than any I had seen. It contained a mass of news of great
interest to us, and one short paragraph which I thought extremely
mischievous. I think it was an editorial, to the effect that at last the
editor had the satisfaction to inform his readers that General
Sherman would next be heard from about Goldsboro', because his
supply-vessels from Savannah were known to be rendezvousing at
Morehead City:--Now, I knew that General Hardee had read that
same paper, and that he would be perfectly able to draw his own
inferences. Up to, that moment I had endeavored so to feign to our
left that we had completely, misled our antagonists; but this was no
longer possible, and I concluded that we must be ready, for the
concentration in our front of all the force subject to General Jos.
Johnston's orders, for I was there also informed that he had been
restored to the full command of the Confederate forces in South and
North Carolina.
On the 6th of March I crossed the Pedee, and all the army
marched for Fayetteville: the Seventeenth Corps kept well to the
right, to make room; the Fifteenth Corps marched by a direct road;
the Fourteenth Corps also followed a direct road from Sneedsboro',
where it had crossed the Pedee; and the Twentieth Corps, which had
come into Cheraw for the convenience of the pontoon-bridge,
diverged to the left, so as to enter Fayetteville next after the
Fourteenth Corps, which was appointed to lead into Fayetteville.
Kilpatrick held his cavalry still farther to the left rear on the roads
from Lancaster, by way of Wadesboro' and New Gilead, so as to
cover our trains from Hampton's and Wheeler's cavalry, who had first
retreated toward the north. I traveled with the Fifteenth Corps, and
on the 8th of March reached Laurel Hill, North Carolina. Satisfied
that our troops must be at Wilmington, I determined to send a
message there; I called for my man, Corporal Pike, whom I had
rescued as before described, at Columbia, who was then traveling
with our escort, and instructed him in disguise to work his way to
the Cape Fear River, secure a boat, and float down to Wilmington to
convey a letter, and to report our approach. I also called on General
Howard for another volunteer, and he brought me a very clever
young sergeant, who is now a commissioned officer in the regular
army. Each of these got off during the night by separate routes,
bearing the following message, reduced to the same cipher we used
in telegraphic messages:
HEADQUARTERS MILITARY DIVISION OF THE
MISSISSIPPI
IN THE FIELD, LAUREL HILL, Wednesday, March 8,
1865.
Commanding Officer, Wilmington, North Carolina:
We are marching for Fayetteville, will be there
Saturday, Sunday, and Monday, and will then march for
Goldsboro'.
If possible, send a boat up Cape Fear River, and have
word conveyed to General Schofield that I expect to
meet him about Goldsboro'. We are all well and have
done finely. The rains make our roads difficult, and
may delay us about Fayetteville, in which case I would
like to have some bread, sugar, and coffee. We have
abundance of all else. I expect to reach Goldsboro' by
the 20th instant.
W. T. SHERMAN, Major-General.
On the 9th I was with the Fifteenth Corps, and toward evening
reached a little church called Bethel, in the woods, in which we took
refuge in a terrible storm of rain, which poured all night, making the
roads awful. All the men were at work corduroying the roads, using
fence-rails and split saplings, and every foot of the way had thus to
be corduroyed to enable the artillery and wagons to pass. On the
10th we made some little progress; on the 11th I reached
Fayetteville, and found that General Hardee, followed by Wade
Hampton's cavalry, had barely escaped across Cape Fear River,
burning the bridge which I had hoped to save. On reaching
Fayetteville I found General Slocum already in possession with the
Fourteenth Corps, and all the rest of the army was near at hand. A
day or two before, General Kilpatrick, to our left rear, had divided his
force into two parts, occupying roads behind the Twentieth Corps,
interposing between our infantry columns and Wade Hampton's
cavalry. The latter, doubtless to make junction with General Hardee,
in Fayetteville, broke across this line, captured the house in which
General Kilpatrick and the brigade-commander, General Spencer,
were, and for a time held possession of the camp and artillery of the
brigade. However, General Kilpatrick and most of his men escaped
into a swamp with their arms, reorganized and returned, catching
Hampton's men--in turn, scattered and drove them away, recovering
most of his camp and artillery; but Hampton got off with Kilpatrick's
private horses and a couple hundred prisoners, of which he boasted
much in passing through Fayetteville.
It was also reported that, in the morning after Hardee's army was
all across the bridge at Cape Fear River, Hampton, with a small
bodyguard, had remained in town, ready to retreat and burn the
bridge as soon as our forces made their appearance. He was getting
breakfast at the hotel when the alarm was given, when he and his
escort took saddle, but soon realized that the alarm came from a set
of our foragers, who, as usual, were extremely bold and rash. On
these he turned, scattered them, killing some and making others
prisoners; among them General Howard's favorite scout, Captain
Duncan. Hampton then crossed the bridge and burned it.
I took up my quarters at the old United States Arsenal, which was
in fine order, and had been much enlarged by the Confederate
authorities, who never dreamed that an invading army would reach
it from the west; and I also found in Fayetteville the widow and
daughter of my first captain (General Childs), of the Third Artillery,
learned that her son Fred had been the ordnance-officer in charge of
the arsenal, and had of course fled with Hardee's army.
During the 11th. the whole army closed down upon Fayetteville,
and immediate preparations were made to lay two pontoon bridges,
one near the burned bridge, and another about four miles lower
down.
Sunday, March 12th, was a day of Sabbath stillness in Fayetteville.
The people generally attended their churches, for they were a very
pious people, descended in a large measure from the old Scotch
Covenanters, and our men too were resting from the toils and labors
of six weeks of as hard marching as ever fell to the lot of soldiers.
Shortly after noon was heard in the distance the shrill whistle of a
steamboat, which came nearer and nearer, and soon a shout, long
and continuous, was raised down by the river, which spread farther
and farther, and we all felt that it meant a messenger from home.
The effect was electric, and no one can realize the feeling unless,
like us, he has been for months cut off from all communication with
friends, and compelled to listen to the croakings and
prognostications of open enemies. But in a very few minutes came
up through the town to the arsenal on the plateau behind a group of
officers, among whom was a large, florid seafaring man, named
Ainsworth, bearing a small mail-bag from General Terry, at
Wilmington, having left at 2 p.m. the day before. Our couriers had
got through safe from Laurel Hill, and this was the prompt reply.
As in the case of our former march from Atlanta, intense anxiety
had been felt for our safety, and General Terry had been prompt to
open communication. After a few minutes' conference with Captain
Ainsworth about the capacity of his boat, and the state of facts
along the river, I instructed him to be ready to start back at 6 p.m.,
and ordered Captain Byers to get ready to carry dispatches to
Washington. I also authorized General Howard to send back by this
opportunity some of the fugitives who had traveled with his army all
the way from Columbia, among whom were Mrs. Feaster and her
two beautiful daughters.
I immediately prepared letters for Secretary Stanton, Generals
Halleck and Grant, and Generals Schofield, Foster, Easton, and
Beckwith, all of which have been published, but I include here only
those to the Secretary of War, and Generals Grant and Terry, as
samples of the whole:
HEADQUARTERS MILITARY DIVISION OF THE
MISSISSIPPI, IN THE FIELD, FAYETTVILLE, NORTH
CAROLINA, Sunday, March. 12, 1885.
Hon. E. M. STANTON, Secretary of War.
DEAR SIR: I know you will be pleased to hear that my
army has reached this point, and has opened
communication with Wilmington. A tug-boat came up
this morning, and will start back at 6 P. M.
I have written a letter to General Grant, the substance
of which he will doubtless communicate, and it must
suffice for me to tell you what I know will give you
pleasure--that I have done all that I proposed, and the
fruits seem to me ample for the time employed.
Charleston, Georgetown, and Wilmington, are
incidents, while the utter demolition of the railroad
system of South Carolina, and the utter destruction of
the enemy's arsenals of Columbia, Cheraw, and
Fayetteville, are the principals of the movement. These
points were regarded as inaccessible to us, and now
no place in the Confederacy is safe against the army of
the West. Let Lee hold on to Richmond, and we will
destroy his country; and then of what use is
Richmond. He must come out and fight us on open
ground, and for that we must ever be ready. Let him
stick behind his parapets, and he will perish.
I remember well what you asked me, and think I am
on the right road, though a long one. My army is as
united and cheerful as ever, and as full of confidence in
itself and its leaders. It is utterly impossible for me to
enumerate what we have done, but I inclose a slip just
handed me, which is but partial. At Columbia and
Cheraw we destroyed nearly all the gunpowder and
cartridges which the Confederacy had in this part of
the country. This arsenal is in fine order, and has been
much enlarged. I cannot leave a detachment to hold it,
therefore shall burn it, blow it up with gunpowder, and
then with rams knock down its walls. I take it for
granted the United States will never again trust North
Carolina with an arsenal to appropriate at her
pleasure.
Hoping that good fortune may still attend my army. I
remain your servant,
W. T. SHERMAN, Major-General.
HEADQUARTERS MILITARY DIVISION OF THE
MISSISSIPPI, IN THE FIELD,
FAYETTVILLE, NORTH CAROLINA, Sunday, March. 12,
1885.
Lieutenant-General U. S. GRANT, commanding United
States Army, City Point, Virginia.
DEAR GENERAL: We reached this place yesterday at
noon; Hardee, as usual, retreating across the Cape
Fear, burning his bridges; but our pontoons will be up
to-day, and, with as little delay as possible, I will be
after him toward Goldsboro'.
A tug has just come up from Wilmington, and before I
get off from here, I hope to get from Wilmington some
shoes and stockings, sugar, coffee, and flour. We are
abundantly supplied with all else, having in a measure
lived off the country.
The army is in splendid health, condition, and spirits,
though we have had foul weather, and roads that
would have stopped travel to almost any other body of
men I ever heard of.
Our march, was substantially what I designed--straight
on Columbia, feigning on Branchville and Augusta. We
destroyed, in passing, the railroad from the Edisto
nearly up to Aiken; again, from Orangeburg to the
Congaree; again, from Colombia down to Kingsville on
the Wateree, and up toward Charlotte as far as the
Chester line; thence we turned east on Cheraw and
Fayetteville. At Colombia we destroyed immense
arsenals and railroad establishments, among which
wore forty-three cannon. At Cheraw we found also
machinery and material of war sent from Charleston,
among which were twenty-five guns and thirty-six
hundred barrels of powder; and here we find about
twenty guns and a magnificent United States' arsenal.
We cannot afford to leave detachments, and I shall
therefore destroy this valuable arsenal, so the enemy
shall not have its use; and the United States should
never again confide such valuable property to a people
who have betrayed a trust.
I could leave here to-morrow, but want to clear my
columns of the vast crowd of refugees and negroes
that encumber us. Some I will send down the river in
boats, and the rest to Wilmington by land, under small
escort, as soon as we are across Cape Fear River.
I hope you have not been uneasy about us, and that
the fruits of this march will be appreciated. It had to
be made not only to destroy the valuable depots by
the way, but for its incidents in the necessary fall of
Charleston, Georgetown, and Wilmington. If I can now
add Goldsboro' without too much cost, I will be in a
position to aid you materially in the spring campaign.
Jos. Johnston may try to interpose between me here
and Schofield about Newbern; but I think he will not
try that, but concentrate his scattered armies at
Raleigh, and I will go straight at him as soon as I get
our men reclothed and our wagons reloaded.
Keep everybody busy, and let Stoneman push toward
Greensboro' or Charlotte from Knoxville; even a feint in
that quarter will be most important.
The railroad from Charlotte to Danville is all that is left
to the enemy, and it will not do for me to go there, on
account of the red-clay hills which are impassable to
wheels in wet weather.
I expect to make a junction with General Schofield in
ten days.
Yours truly,
W. T. SHERMAN, Major-General.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

Instant download Developing Backbone js Applications Addy Osmani pdf all chapter

  • 1.
    Visit https://ebookultra.com todownload the full version and explore more ebooks Developing Backbone js Applications Addy Osmani _____ Click the link below to download _____ https://ebookultra.com/download/developing-backbone-js- applications-addy-osmani/ Explore and download more ebooks at ebookultra.com
  • 2.
    Here are somesuggested products you might be interested in. Click the link to download Building Node Applications with MongoDB and Backbone 1st Edition Mike Wilson https://ebookultra.com/download/building-node-applications-with- mongodb-and-backbone-1st-edition-mike-wilson/ Developing Mainframe Java Applications 1st Edition Lou Marco https://ebookultra.com/download/developing-mainframe-java- applications-1st-edition-lou-marco/ Developing applications with enterprise SOA 1st Edition Martin Huvar https://ebookultra.com/download/developing-applications-with- enterprise-soa-1st-edition-martin-huvar/ Enterprise J2ME developing mobile Java applications 8th print Edition Yuan https://ebookultra.com/download/enterprise-j2me-developing-mobile- java-applications-8th-print-edition-yuan/
  • 3.
    Developing Facebook PlatformApplications with Rails 1st Edition Michael J. Mangino https://ebookultra.com/download/developing-facebook-platform- applications-with-rails-1st-edition-michael-j-mangino/ Women Writing Africa West Africa and the Sahel Esi Sutherland-Addy https://ebookultra.com/download/women-writing-africa-west-africa-and- the-sahel-esi-sutherland-addy/ Flask Web Development Developing Web Applications With Python 2nd Edition Miguel Grinberg https://ebookultra.com/download/flask-web-development-developing-web- applications-with-python-2nd-edition-miguel-grinberg/ Developing Essbase Applications Hybrid Techniques and Practices 2nd Edition Cameron Lackpour (Editor) https://ebookultra.com/download/developing-essbase-applications- hybrid-techniques-and-practices-2nd-edition-cameron-lackpour-editor/ Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier https://ebookultra.com/download/developing-android-applications-with- adobe-air-1st-edition-veronique-brossier/
  • 5.
    Developing Backbone jsApplications Addy Osmani Digital Instant Download Author(s): Addy Osmani ISBN(s): 9781449328252, 1449328253 Edition: Early release File Details: PDF, 2.54 MB Year: 2012 Language: english
  • 7.
    Developing Backbone.js Applications Addy Osmani Beijing• Cambridge • Farnham • Köln • Sebastopol • Tokyo
  • 8.
    Developing Backbone.js Applications byAddy Osmani Revision History for the : 2012-04-19 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449328252 for release details. ISBN: 978-1-449-32825-2 1335306849
  • 9.
    Table of Contents Prelude. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Fundamentals 2 MVC, MVP & Backbone.js 2 MVC 2 Smalltalk-80 MVC 2 MVC As We Know It 3 Models 4 Views 5 Controllers 8 Controllers in Spine.js vs Backbone.js 8 What does MVC give us? 10 Delving deeper 10 Summary 11 MVP 11 Models, Views & Presenters 11 MVP or MVC? 12 MVC, MVP and Backbone.js 13 Fast facts 15 Backbone.js 15 2. The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 What is Backbone? 17 Why should you consider using it? 17 The Basics 17 Models 18 Views 21 Creating new views 21 What is el? 22 Collections 23 iii
  • 10.
    Underscore utility functions25 Routers 25 Backbone.history 27 Namespacing 27 What is namespacing? 28 Additional Tips 31 Automated Backbone Scaffolding 31 Is there a limit to the number of routers I should be using? 32 Is Backbone too small for my application’s needs? 32 3. RESTful Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Building RESTful applications with Backbone 33 Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB 33 Reviewing the stack 33 Practical 34 Practical Setup 40 Building Backbone.js Apps With Ruby, Sinatra, MongoDB and Haml 42 Introduction 42 What Is Sinatra? 42 Getting Started With Sinatra 43 Templating And HAML 45 MongoDB Ruby Driver 47 Getting started 47 Practical 48 Installing The Prerequisites 48 Tutorial 50 Conclusions 57 4. Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Modular JavaScript 59 Organizing modules with RequireJS and AMD 59 Writing AMD modules with RequireJS 60 Keeping Your Templates External Using RequireJS And The Text Plugin 63 Optimizing Backbone apps for production with the RequireJS Optimizer 65 Practical: Building a modular Backbone app with AMD & RequireJS 67 Overview 67 Markup 68 Configuration options 69 Modularizing our models, views and collections 70 Decoupling Backbone with the Mediator and Facade patterns 75 Summary 75 Practical 76 iv | Table of Contents
  • 11.
    Paginating Backbone.js Requests& Collections 82 Paginator’s pieces 83 Downloads And Source Code 83 Live Examples 84 Paginator.requestPager 86 1. Create a new Paginated collection 86 2: Set the model and base URL for the collection as normal 86 3. Map the attributes supported by your API (URL) 87 4. Configure the default pagination, query and sort details for the pag- inator 87 5. Finally, configure Collection.parse() and we’re done 88 Convenience methods: 89 Paginator.clientPager 89 1. Create a new paginated collection with a model and URL 89 2. Map the attributes supported by your API (URL) 90 3. Configure how to paginate data at a UI-level 90 4. Configure the rest of the request parameter default values 90 5. Finally, configure Collection.parse() and we’re done 91 Convenience methods: 91 Views/Templates 91 Backbone & jQuery Mobile 94 Resolving the routing conflicts 94 Practical: A Backbone, RequireJS/AMD app with jQuery Mobile 95 Getting started 95 jQuery Mobile: Going beyond mobile application development 96 5. Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Unit Testing Backbone Applications With Jasmine 99 Introduction 99 Jasmine 99 Suites, Specs & Spies 101 beforeEach and afterEach() 104 Shared scope 104 Getting setup 105 TDD With Backbone 105 Models 105 Collections 108 Views 110 Initial setup 111 View rendering 113 Rendering with a templating system 116 Conclusions 118 Exercise 118 Table of Contents | v
  • 12.
    Further reading 118 UnitTesting Backbone Applications With QUnit And SinonJS 119 Introduction 119 QUnit 119 Getting Setup 119 Assertions 120 Adding structure to assertions 124 Assertion examples 125 Fixtures 127 Asynchronous code 129 SinonJS 130 What is SinonJS? 130 Stubs and mocks 133 Practical 135 Models 135 Collections 137 Views 138 Events 139 App 141 Further Reading & Resources 142 6. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 7. Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 vi | Table of Contents
  • 13.
    Prelude Welcome to my(in-progress) book about the Backbone.js framework for structuring JavaScript applications. It’s released under a Creative Commons Attribution-Non- Commercial-ShareAlike 3.0 Unported license meaning you can both grab a copy of the book for free or help to further improve it. I’m very pleased to announce that this book will be out in physical form in a few months time via O’Reilly Media. Readers will have the option of purchasing the latest version in either print or a number of digital formats then or can grab a recent version from this repository. Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help. My extended thanks go out to Jeremy Ashkenas for creating Backbone.js and these members of the com- munity for their assistance tweaking this project. I hope you find this book helpful! vii
  • 15.
    CHAPTER 1 Introduction As JavaScriptdevelopers, we are at an interesting point in time where not only do we have mature solutions to help organize the JavaScript powering our applications based on a separation of concerns, but developers looking to build non-trivial projects are almost spoiled for choice for frameworks that can help structure their applications. Maturity in software (framework) development isn’t simply about how long a frame- work has been around. It’s about how solid the framework is and more importantly how well it’s evolved to fill its role. Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it? In this book, I will be covering the popular Backbone.js, which I consider the best of the current family of JavaScript architectural frameworks. Topics will include MVC theory and how to build applications using Backbone’s mod- els, views, collections and routers. I’ll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), how to build ap- plications using modern software stacks (like Node and Express), how to solve the routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and a lot more. If this is your first time looking at Backbone.js and you’re still unsure whether or not to give it a try, why not take a look at how a Todo application can be implemented in Backbone and several other popular Javascript frameworks before reading further? The goal of this book is to create an authoritative and centralized repository of infor- mation that can help those developing real-world apps with Backbone. If you come across a section or topic which you think could be improved or expanded on, please feel free to submit a pull-request. It won’t take long and you’ll be helping other devel- opers avoid problems you’ve run into before. 1
  • 16.
    Fundamentals In this sectionwe are going to cover the context into which a framework like Back- bone.js fits. Let’s begin our journey into understanding Backbone better with a look at code architecture. MVC, MVP & Backbone.js Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns. Design patterns are proven solutions to common development problems and can suggest structural approaches to help guide developers in adding some organization to their applications. Patterns are useful because they’re a set of practices that build upon the collective experience of skilled developers who have repeatedly solved similar problems. Al- though developers 10 or 20 years ago may not have been using the same programming languages when implementing patterns in their projects, there are many lessons we can learn from their efforts. In this section, we’re going to review two popular patterns - MVC and MVP. We’ll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in. MVC MVC (Model-View-Controller) is an architectural design pattern that encourages im- proved application organization through a separation of concerns. It enforces the iso- lation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally present to manage logic, user-input and the coordination of models and views. The pattern was originally designed by Trygve Reenskaug while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller- Editor. MVC was described in depth in “Design Patterns: Elements of Reusable Object- Oriented Software” (The “GoF” or “Gang of Four” book) in 1994, which played a role in popularizing its use. Smalltalk-80 MVC It’s important to understand what the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70’s, graphical user- interfaces were far and few between. An approach known as Separated Presentation began to be used as a means to make a clear division between domain objects which modeled concepts in the real world (e.g a photo, a person) and the presentation objects which were rendered to the user’s screen. 2 | Chapter 1: Introduction
  • 17.
    The Smalltalk-80 implementationof MVC took this concept further and had an ob- jective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of models for other interfaces in the application. There are some interesting points worth noting about Smalltalk-80’s MVC architecture: • A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers) • Presentation was taken care of by the View and the Controller, but there wasn’t just a single view and controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them • The Controller’s role in this pair was handling user input (such as key-presses and click events), doing something sensible with them. • The Observer pattern was relied upon for updating the View whenever the Model changed Developers are sometimes surprised when they learn that the Observer pattern (nowa- days commonly implemented as a Publish/Subscribe system) was included as a part of MVC’s architecture decades ago. In Smalltalk-80’s MVC, the View and Controller both observe the Model: anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - for the application to show real- time information, any change to the data in its Models should result in the View being refreshed instantly. Martin Fowler has done an excellent job of writing about the origins of MVC over the years and if you are interested in further historical information about Smalltalk-80’s MVC, I recommend reading his work. MVC As We Know It We’ve reviewed the 70’s, but let us now return to the here and now. The MVC pattern has been applied to a diverse range of programming languages. For example, the pop- ular Ruby on Rails is an implementation of a web application framework based on MVC for the Ruby language. JavaScript now has a number of MVC frameworks, in- cluding Ember.js, JavaScriptMVC, and of course Backbone.js. Given the importance of avoiding “spaghetti” code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let’s look at what the MVC pattern enables the Javascript developer to do. MVC is composed of three core components: MVC As We Know It | 3
  • 18.
    Models Models manage thedata for an application. They are concerned with neither the user- interface nor presentation layers, but instead represent structured data that an appli- cation may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has oc- curred so that they may react accordingly. To understand models better, let us imagine we have a JavaScript photo gallery appli- cation. In a photo gallery, a photo would merit its own model, as it represents a unique kind of domain-specific data. The Photo model may represent attributes such as a caption, image source and additional meta-data. A specific photo would be stored in an instance of a model. Here’s an example of a simple Photo model implemented with Backbone.js: var Photo = Backbone.Model.extend({ // Default attributes for the photo defaults: { // Ensure that each photo created has an `src`. src: "placeholder.jpg", caption: "A default image", viewed: false }, initialize: function() { } }); The built-in capabilities of models vary across frameworks, however it’s common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also need a way of persisting models. Persistence allows us to edit and update models with the knowledge that their most recent states will be saved some- where, for example in a web browser’s localStorage data-store or synchronized with a database. A model may also have multiple views observing it. Imagine our Photo model contained meta-data such as the longitude and latitude where the photo was taken, a list of people present in the photo, and a list of tags. A developer could create a single view that displayed all these attributes, or might create three separate views to display each at- tribute. The important detail is that the Photo model doesn’t care how these views are organized, it simply announces updates to its data as necessary. We’ll come back to Views in more detail later. It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called “Collections”. Managing models in groups allows us to write application logic based on notifications from the group, 4 | Chapter 1: Introduction
  • 19.
    should any modelit contains change. This avoids the need to manually observe indi- vidual model instances. Here’s how we might group Photo models into a simplified Backbone Collection: var PhotoGallery = Backbone.Collection.extend({ // Reference to this collection's model. model: Photo, // Filter down the list of all photos that have been viewed viewed: function() { return this.filter(function(photo){ return photo.get('viewed'); }); }, // Filter down the list to only photos that have not yet been viewed unviewed: function() { return this.without.apply(this, this.viewed()); } }); If you read older texts on MVC, you may come across a description of models as also managing application “state”. In JavaScript applications “state” has a specific meaning, typically referring to the current “state” of a view or sub-view on a user’s screen at a fixed time. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated. Views Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, al- lowing the view to update itself accordingly. Design pattern literature commonly refers to views as “dumb”, given that their knowledge of models and controllers in an appli- cation is limited. Users interact with views, which usually means reading and editing model data. For example, in our photo gallery application example, model viewing might happen in a user interface with a big image, a caption, and a list of tags. Model editing could be done through an “edit” view where a user who has selected a specific photo could edit its caption, tags, or other metadata in a form. In MVC, the actual task of updating the Model falls to Controllers, which we’ll be covering shortly. Let’s explore Views a little further using a simple JavaScript example. Below we can see a function that creates a single Photo view, consuming both a model instance and a controller instance. MVC As We Know It | 5
  • 20.
    We define arender() utility within our view which is responsible for rendering the contents of the photoModel using a JavaScript templating engine (Underscore templat- ing) and updating the contents of our view, referenced by photoEl. The photoModel then adds our render() callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes. You may wonder where user interaction comes into play here. When users click on any elements within the view, it’s not the view’s responsibility to know what to do next. A Controller makes this decision. In our sample implementation, this is achieved by adding an event listener to photoEl which will delegate handling the click behavior back to the controller, passing the model information along with it in case it’s needed. The benefit of this architecture is that each component plays its own separate role in making the application function as needed. var buildPhotoView = function( photoModel, photoController ){ var base = document.createElement('div'), photoEl = document.createElement('div'); base.appendChild(photoEl); var render= function(){ // We use a templating library such as Underscore // templating which generates the HTML for our // photo entry photoEl.innerHTML = _.template('photoTemplate', {src: photoModel.getSrc()}); } photoModel.addSubscriber( render ); photoEl.addEventListener('click', function(){ photoController.handleEvent('click', photoModel ); }); var show = function(){ photoEl.style.display = ''; } var hide = function(){ photoEl.style.display = 'none'; } return{ showView: show, hideView: hide } } Templating 6 | Chapter 1: Introduction
  • 21.
    In the contextof JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views. It has long been considered bad practice (and computationally expensive) to manually create large blocks of HTML markup in-memory through string concatenation. De- velopers using this technique often find themselves iterating through their data, wrap- ping it in nested divs and using outdated techniques such as document.write to inject the “template” into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications. JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to define templates for views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g “text/template”). Variables are delimited using a variable syntax (e.g {{name}}). Javascript template libraries typically accept data in JSON, and the grunt work of pop- ulating templates with data is taken care of by the framework itself. This has a several benefits, particularly when opting to store templates externally as this can let applica- tions load templates dynamically on an as-needed basis. Let’s compare two examples of HTML templates. One is implemented using the pop- ular Handlebars.js library, and the other uses Underscore’s “microtemplates”. Handlebars.js: <li class="photo"> <h2>{{caption}}</h2> <img class="source" src="{{src}}"/> <div class="meta-data"> {{metadata}} </div> </li> Underscore.js Microtemplates: <li class="photo"> <h2><%= caption %></h2> <img class="source" src="<%= src %>"/> <div class="meta-data"> <%= metadata %> </div> </li> You may also use double curly brackets (i.e {{}}) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore templateSettings attribute as follows: _.templateSettings = { interpolate : /{{(.+?)}}/g }; A note on navigation and state It is also worth noting that in classical web development, navigating between inde- pendent views required the use of a page refresh. In single-page JavaScript applications, MVC As We Know It | 7
  • 22.
    however, once datais fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn’t automatically update the URL, the role of navigation thus falls to a “router”, which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section. Controllers Controllers are an intermediary between models and views which are classically re- sponsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view. In our photo gallery application, a controller would be responsible for handling changes the user made to the edit view for a particular photo, updating a specific photo model when a user has finished editing. It’s with controllers that most JavaScript MVC frameworks depart from this interpre- tation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript framework authors likely initially looked at server-side interpretations of MVC (such as Ruby on Rails), realized that that approach didn’t translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the “proper” role of controllers in other non-Javascript frameworks. So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain “controller” logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC. In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It’s in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects. Controllers in Spine.js vs Backbone.js Spine.js We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). Since Backbone doesn’t have its own explicit controllers, it’s useful to review the controller from another MVC framework to appreciate the difference in implementations. Let’s take a look at Spine.js: 8 | Chapter 1: Introduction
  • 23.
    In this example,we’re going to have a controller called PhotosController which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user edited the photo meta-data) the corresponding model does too. (Note: We won’t be delving heavily into Spine.js beyond this example, but it’s worth looking at it to learn more about Javascript frameworks in general.) // Controllers in Spine are created by inheriting from Spine.Controller var PhotosController = Spine.Controller.sub({ init: function(){ this.item.bind("update", this.proxy(this.render)); this.item.bind("destroy", this.proxy(this.remove)); }, render: function(){ // Handle templating this.replace($("#photoTemplate").tmpl(this.item)); return this; }, remove: function(){ this.$el.remove(); this.release(); } }); In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller). What we’re doing in the above example is setting up listeners in the update and destroy events using render() and remove(). When a photo entry gets updated, we re- render the view to reflect the changes to the meta-data. Similarly, if the photo gets deleted from the gallery, we remove it from the view. In case you were wondering about the tmpl() function in the code snippet: in the render() function, we’re using this to render a JavaScript template called #photoTemplate which simply returns a HTML string used to replace the controller’s current element. Whatthisprovidesuswithisaverylightweight,simplewaytomanagechangesbetween the model and the view. Backbone.js Later on in this section we’re going to revisit the differences between Backbone and traditional MVC, but for now let’s focus on controllers. In Backbone, controller logic is shared between Backbone.View and Backbone.Router. Earlier releases of Backbone contained something called Backbone.Controller, but it was renamed to Router to clarify its role. A Router’s main purpose is to translate URL requests into application states. When a user browses to the URL www.example.com/photos/42, a Router could be used to MVC As We Know It | 9
  • 24.
    show the photowith that ID, and to define what application behavior should be run in response to that request. Routers can contain traditional controller responsibilities, such as binding the events between models and views, or rendering parts of the page. However, Backbone contributor Tim Branyen has pointed out that it’s possible to get away without needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably: var PhotoRouter = Backbone.Router.extend({ routes: { "photos/:id": "route" }, route: function(id) { var item = photoCollection.get(id); var view = new PhotoView({ model: item }); something.html( view.render().el ); } }): What does MVC give us? To summarize, the separation of concerns in MVC facilitates modularization of an application’s functionality and enables: • Easier overall maintenance. When updates need to be made to the application it is clear whether the changes are data-centric, meaning changes to models and pos- sibly controllers, or merely visual, meaning changes to views. • Decoupling models and views means that it’s straight-forward to write unit tests for business logic • Duplication of low-level model and controller code is eliminated across the appli- cation • Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user- interfaces to work simultaneously Delving deeper Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we’ll explore it a little further. The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a “set of classes to build a user interface”. In their view, it’s actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I’ve covered some of these patterns in my other free book, JavaScript Design Patterns For Beginners if you would like to read into them further. 10 | Chapter 1: Introduction
  • 25.
    As we’ve discussed,models represent application data, while views handle what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core com- munication (something that surprisingly isn’t covered in many articles about the MVC pattern). When a model is changed it “publishes” to the rest of the application that it has been updated. The “subscriber”–generally a Controller–then updates the view ac- cordingly. The observer-viewer nature of this relationship is what facilitates multiple views being attached to the same model. For developers interested in knowing more about the decoupled nature of MVC (once again, depending on the implementation), one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different re- lationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern. Summary Having reviewed the classical MVC pattern, your should now understand how it allows developers to cleanly separate concerns in an application. You should also now appre- ciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern. When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it’s opted to approach Models, Views, Controllers or other alternatives, as this can better help you grok how the framework expects to be used. MVP Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named Taligent in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple compo- nents, there are some fundamental differences between them. For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures. Models, Views & Presenters The P in MVP stands for presenter. It’s a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests. MVP | 11
  • 26.
    The most commonimplementation of MVP is one which uses a Passive View (a view which is for all intents and purposes “dumb”), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts asamediatorwhichtalkstoboththeviewandmodel,howeverbothoftheseareisolated from each other. They effectively bind models to views, a responsibility held by Con- trollers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views. Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it’s the presenter’s role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data. The benefit of this change from MVC is that it increases the testability of your appli- cation and provides a more clean separation between the view and the model. This isn’t however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately. Although a common implementation of a Passive View is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don’t have the interface construct in Java- Script, we’re using it more as more a protocol than an explicit interface here. It’s tech- nically still an API and it’s probably fair for us to refer to it as an interface from that perspective. There is also a Supervising Controller variation of MVP, which is closer to the MVC and MVVM patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey’s Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone. MVP or MVC? MVP is generally used most often in enterprise-level applications where it’s necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn’t quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly. As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application. 12 | Chapter 1: Introduction
  • 27.
    Depending on theimplementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other compo- nents. In my experience this really depends on the languages you are implementing MVP in (there’s quite a difference between opting for MVP for a JavaScript project over one for say, ASP.net). At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for. MVC, MVP and Backbone.js There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVP patterns in their classical form as many JavaScript developers don’t view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.net or GWT). This is because it’s possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC. Backbone contributor Irene Ros subscribes to this way of thinking as when she sepa- rates Backbone views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a Back bone.Router, covered later in the book) or a callback in response to data being fetched. That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that: • The presenter in MVP better describes the Backbone.View (the layer between View templates and the data bound to it) than a controller does • The model fits Backbone.Model (it isn’t that different from the classical MVC “Model”) • The views best represent templates (e.g Handlebars/Mustache markup templates) A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by Backbone.View because they’re able to ach- ieve two purposes: both rendering atomic components and assembling those compo- nents rendered by other views. We’ve also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true. MVC, MVP and Backbone.js | 13
  • 28.
    Here, our BackbonePhotoView uses the Observer pattern to “subscribe” to changes to a View’s model in the line this.model.on('change',...). It also handles templating in the render() method, but unlike some other implementations, user interaction is also handled in the View (see events). var PhotoView = Backbone.View.extend({ //... is a list tag. tagName: "li", // Pass the contents of the photo template through a templating // function, cache it for a single photo template: _.template($('#photo-template').html()), // The DOM events specific to an item. events: { "click img" : "toggleViewed" }, // The PhotoView listens for changes to its model, re-rendering. Since there's // a one-to-one correspondence between a **Photo** and a **PhotoView** in this // app, we set a direct reference on the model for convenience. initialize: function() { _.bindAll(this, 'render'); this.model.on('change', this.render); this.model.on('destroy', this.remove); }, // Re-render the photo entry render: function() { this.$el.html(this.template(this.model.toJSON())); return this; }, // Toggle the `"viewed"` state of the model. toggleViewed: function() { this.model.viewed(); } }); Another (quite different) opinion is that Backbone more closely resembles Smalltalk-80 MVC, which we went through earlier. As regular Backbone user Derick Bailey has written, it’s ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone doesn’t fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well. Call it the Backbone way, MV* or whatever helps reference its flavor of appli- cation architecture. 14 | Chapter 1: Introduction
  • 29.
    It is howeverworth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained. Fast facts Backbone.js • Core components: Model, View, Collection, Router. Enforces its own flavor of MV* • Good documentation, with more improvements on the way • Used by large companies such as SoundCloud and Foursquare to build non-trivial applications • Event-driven communicationbetweenviewsandmodels. Aswe’llsee,it’srelatively straight-forwardtoaddeventlistenerstoanyattributeinamodel,givingdevelopers fine-grained control over what changes in the view • Supports data bindings through manual events or a separate Key-value observing (KVO) library • Great support for RESTful interfaces out of the box, so models can be easily tied to a backend • Extensive eventing system. It’s trivial to add support for pub/sub in Backbone • Prototypes are instantiated with the new keyword, which some developers prefer • Agnostic about templating frameworks, however Underscore’s micro-templating is available by default. Backbone works well with libraries like Handlebars • Doesn’t support deeply nested models, though there are Backbone plugins such as this which can help • Clear and flexible conventions for structuring applications. Backbone doesn’t force usage of all of its components and can work with only those needed. Fast facts | 15
  • 31.
    CHAPTER 2 The Basics Whatis Backbone? Backbone.js is one of a number of JavaScript frameworks for creating MVC-like web applications. On the front-end, it’s my architectural framework of choice as it’s both mature, relatively lightweight and can be easily tested using third-party toolkits such as Jasmine or QUnit. Other MVC frameworks you may be familiar with include Em- ber.js (SproutCore 2.0), Spine, YUILibrary and JavaScriptMVC. Backbone is maintained by a number of contributors, most notably: Jeremy Ashkenas, creator of CoffeeScript, Docco and Underscore.js. As Jeremy is a believer in detailed documentation, there’s a level of comfort in knowing you’re unlikely to run into issues which are either not explained in the official docs or which can’t be nailed down with some assistance from the #documentcloud IRC channel. I strongly recommend using the latter if you find yourself getting stuck. Why should you consider using it? Backbone’s main benefits, regardless of your target platform or device, include helping: • Organize the structure to your application • Simplify server-side persistence • Decouple the DOM from your page’s data • Model data, views and routers in a succinct manner • Provide DOM, model and collection synchronization The Basics In this section, you’ll learn the essentials of Backbone’s models, views, collections and routers, as well as about using namespacing to organize your code. This isn’t meant as 17
  • 32.
    a replacement forthe official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications with it. • Models • Collections • Routers • Views • Namespacing Models Backbone models contain interactive data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a photo object including its attributes like tags, titles and a location. Models can be created by extending Backbone.Model as follows: var Photo = Backbone.Model.extend({ defaults: { src: 'placeholder.jpg', title: 'an image placeholder', coordinates: [0,0] }, initialize: function(){ this.on("change:src", function(){ var src = this.get("src"); console.log('Image source updated to ' + src); }); }, changeSrc: function( source ){ this.set({ src: source }); } }); var somePhoto = new Photo({ src: "test.jpg", title:"testing"}); somePhoto.changeSrc("magic.jpg"); // which triggers "change:src" and logs an update message to the conso Initialization The initialize() method is called when a new instance of a model is created. Its use is optional, however you’ll see why it’s good practice to use it below. var Photo = Backbone.Model.extend({ initialize: function(){ console.log('this model has been initialized'); } }); // We can then create our own instance of a photo as follows: var myPhoto = new Photo(); 18 | Chapter 2: The Basics
  • 33.
    Getters & Setters Model.get() Model.get()provides easy access to a model’s attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval. var myPhoto = new Photo({ title: "My awesome photo", src:"boston.jpg", location: "Boston", tags:['the big game', 'vacation']}), title = myPhoto.get("title"), //My awesome photo location = myPhoto.get("location"), //Boston tags = myPhoto.get("tags"), // ['the big game','vacation'] photoSrc = myPhoto.get("src"); //boston.jpg Alternatively, if you wish to directly access all of the attributes in a model’s instance directly, you can achieve this as follows: var myAttributes = myPhoto.attributes; console.log(myAttributes); It is best practice to use Model.set() or direct instantiation to set the values of a model’s attributes. Accessing Model.attributes directly is generally discouraged. Instead, should you need to read or clone data, Model.toJSON() is recommended for this purpose. If you would like to access or copy a model’s attributes for purposes such as JSON stringification (e.g. for serialization prior to being passed to a view), this can be achieved using Model.toJSON(): var myAttributes = myPhoto.toJSON(); console.log(myAttributes); /* this returns { title: "My awesome photo", src:"boston.jpg", location: "Boston", tags:['the big game', 'vacation']}*/ Model.set() Model.set() allows us to pass attributes into an instance of our model. Attributes can either be set during initialization or at any time afterwards. It’s important to avoid trying to set a Model’s attributes directly (for example Model.caption = “A new caption”). Backbone uses Model.set() to know when to broadcast that a model’s data has changed. var Photo = Backbone.Model.extend({ initialize: function(){ console.log('this model has been initialized'); } }); // Setting the value of attributes via instantiation var myPhoto = new Photo({ title: 'My awesome photo', location: 'Boston' }); The Basics | 19
  • 34.
    var myPhoto2 =new Photo(); // Setting the value of attributes through Model.set() myPhoto2.set({ title:'Vacation in Florida', location: 'Florida' }); Default values There are times when you want your model to have a set of default values (e.g. in a scenario where a complete set of data isn’t provided by the user). This can be set using a property called defaults in your model. var Photo = Backbone.Model.extend({ defaults:{ title: 'Another photo!', tags: ['untagged'], location: 'home', src: 'placeholder.jpg' }, initialize: function(){ } }); var myPhoto = new Photo({ location: "Boston", tags:['the big game', 'vacation']}), title = myPhoto.get("title"), //Another photo! location = myPhoto.get("location"), //Boston tags = myPhoto.get("tags"), // ['the big game','vacation'] photoSrc = myPhoto.get("src"); //placeholder.jpg Listening for changes to your model Any and all of the attributes in a Backbone model can have listeners bound to them which detect when their values change. Listeners can be added to the initialize() function: this.on('change', function(){ console.log('values for this model have changed'); }); In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered. var Photo = Backbone.Model.extend({ defaults:{ title: 'Another photo!', tags: ['untagged'], location: 'home', src: 'placeholder.jpg' }, initialize: function(){ console.log('this model has been initialized'); this.on("change:title", function(){ var title = this.get("title"); console.log("My title has been changed to.. " + title); }); }, 20 | Chapter 2: The Basics
  • 35.
    setTitle: function(newTitle){ this.set({ title:newTitle }); } }); var myPhoto = new Photo({ title:"Fishing at the lake", src:"fishing.jpg"}); myPhoto.setTitle('Fishing at sea'); //logs 'My title has been changed to.. Fishing at sea' Validation BackbonesupportsmodelvalidationthroughModel.validate(),whichallowschecking the attribute values for a model prior to them being set. Validationfunctions canbeassimpleorcomplex asnecessary.Iftheattributesprovided are valid, nothing should be returned from .validate(). If they are invalid, a custom error can be returned instead. A basic example for validation can be seen below: var Photo = Backbone.Model.extend({ validate: function(attribs){ if(attribs.src === undefined){ return "Remember to set a source for your image!"; } }, initialize: function(){ console.log('this model has been initialized'); this.on("error", function(model, error){ console.log(error); }); } }); var myPhoto = new Photo(); myPhoto.set({ title: "On the beach" }); //logs Remember to set a source for your image! Views Views in Backbone don’t contain the markup for your application, but rather they are there to support models by defining the logic for how they should be represented to the user. This is usually achieved using JavaScript templating (e.g. Mustache, jQuery- tmpl, etc.). A view’s render() function can be bound to a model’s change() event, al- lowing the view to always be up to date without requiring a full page refresh. Creating new views Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend Backbone.View. I’ll explain this code in detail below: Views | 21
  • 36.
    var PhotoSearch =Backbone.View.extend({ el: $('#results'), render: function( event ){ var compiled_template = _.template( $("#results-template").html() ); this.$el.html( compiled_template(this.model.toJSON()) ); return this; //recommended as this enables calls to be chained. }, events: { "submit #searchForm": "search", "click .reset": "reset", "click .advanced": "switchContext" }, search: function( event ){ //executed when a form '#searchForm' has been submitted }, reset: function( event ){ //executed when an element with class "reset" has been clicked. }, switchContext: function( event ){ //executed when an element with class "advanced" has been clicked. } }); What is el? el is basically a reference to a DOM element and all views must have one. It allows for all of the contents of a view to be inserted into the DOM at once, which makes for faster rendering as browser performs the minimum required reflows and repaints. There are two ways to attach a DOM element to a view: the element already exists in the page or a new element is created for the view and added manually by the developer. If the element already exists in the page, you can set el as either a CSS selector that matches the element or a simple reference to the DOM element. el: '#footer', // OR el: document.getElementById( 'footer' ) If you want to create a new element for your view, set any combination of the following view’s properties: tagName, id and className. A new element will be created for you by the framework and a reference to it will be available at the el property. tagName: 'p', // required, but defaults to 'div' if not set className: 'container', // optional, you can assign multiple classes to this property like so 'container id: 'header', // optional The above code creates the DOMElement below but doesn’t append it to the DOM. <p id="header" class="container"></p> Understanding render() 22 | Chapter 2: The Basics
  • 37.
    render() is anoptional function that defines the logic for rendering a template. We’ll use Underscore’s micro-templating in these examples, but remember you can use other templating frameworks if you prefer. The _.template method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the above view, I’m passing the markup from a template with id results-template to _.template() to be compiled. Next, I set the html of the el DOM element to the output of processing a JSON version of the model associated with the view through the compiled template. Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code. The events attribute The Backbone events attribute allows us to attach event listeners to either custom selectors, or directly to el if no selector is provided. An event takes the form {"eventName selector": "callbackFunction"} and a number of event-types are supported, including click, submit, mouseover, dblclick and more. What isn’t instantly obvious is that under the bonnet, Backbone uses jQuery’s .dele gate() toprovideinstantsupportforeventdelegationbutgoesalittlefurther,extending it so that this always refers to the current view object. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corre- sponding function with the same name within the scope of your view. Collections Collections are sets of Models and are created by extending Backbone.Collection. Normally, when creating a collection you’ll also want to pass through a property spec- ifying the model that your collection will contain, as well as any instance properties required. In the following example, we create a PhotoCollection that will contain our Photo models: var PhotoCollection = Backbone.Collection.extend({ model: Photo }); Getters and Setters There are a few different ways to retrieve a model from a collection. The most straight- forward is to use Collection.get() which accepts a single id as follows: var skiingEpicness = PhotoCollection.get(2); Sometimes you may also want to get a model based on its client id. The client id is a property that Backbone automatically assigns models that have not yet been saved. You can get a model’s client id from its .cid property. Collections | 23
  • 38.
    var mySkiingCrash =PhotoCollection.getByCid(456); Backbone Collections don’t have setters as such, but do support adding new models via .add() and removing models via .remove(). var a = new Backbone.Model({ title: 'my vacation'}), b = new Backbone.Model({ title: 'my holiday'}); var photoCollection = new PhotoCollection([a,b]); photoCollection.remove([a,b]); Listening for events As collections represent a group of items, we’re also able to listen for add and remove events for when new models are added or removed from the collection. Here’s an ex- ample: var PhotoCollection = new Backbone.Collection(); PhotoCollection.on("add", function(photo) { console.log("I liked " + photo.get("title") + ' its this one, right? ' + photo.get("src")); }); PhotoCollection.add([ {title: "My trip to Bali", src: "bali-trip.jpg"}, {title: "The flight home", src: "long-flight-oofta.jpg"}, {title: "Uploading pix", src: "too-many-pics.jpg"} ]); In addition, we’re able to bind a change event to listen for changes to models in the collection. PhotoCollection.on("change:title", function(){ console.log('there have been updates made to this collections titles'); }); Fetching models from the server Collections.fetch() retrieves a default set of models from the server in the form of a JSON array. When this data returns, the current collection’s contents will be replaced with the contents of the array. var PhotoCollection = new Backbone.Collection; PhotoCollection.url = '/photos'; PhotoCollection.fetch(); Under the covers, Backbone.sync is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto’s ajax implementations to make these RESTful requests, however this can be overridden as per your needs. In the above example if we wanted to log an event when .sync() was called, we could do this: Backbone.sync = function(method, model) { console.log("I've been passed " + method + " with " + JSON.stringify(model)); }; 24 | Chapter 2: The Basics
  • 39.
    Resetting/Refreshing Collections Rather thanadding or removing models individually, you might occasionally wish to update an entire collection at once. Collection.reset() allows us to replace an entire collection with new models as follows: javascript PhotoCollection.reset([ {title: "My trip to Scotland", src: "scot land-trip.jpg"}, {title: "The flight from Scotland", src: "long-flight.jpg"}, {title: "Latest snap of lock-ness", src: "lockness.jpg"}]); Note that using Col lection.reset() doesn’t fire any add or remove events. A reset event is fired instead. Underscore utility functions As Backbone requires Underscore as a hard dependency, we’re able to use many of the utilities it has to offer to aid with our application development. Here’s an example of how Underscore’s sortBy() method can be used to sort a collection of photos based on a particular attribute. var sortedByAlphabet = PhotoCollection.sortBy(function (photo) { return photo.get("title").toLowerCase(); }); The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official docs. Routers In Backbone, routers are used to help manage application state and for connecting URLs to application events. This is achieved using hash-tags with URL fragments, or using the browser’s pushState and History API. Some examples of routes may be seen below: http://unicorns.com/#whatsup http://unicorns.com/#search/seasonal-horns/page2 Note: An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that particular route. This relationship is defined as follows: "route" : "mappedFunction" Let us now define our first controller by extending Backbone.Router. For the purposes of this guide, we’re going to continue pretending we’re creating a photo gallery appli- cation that requires a GalleryRouter. Note the inline comments in the code example below as they continue the rest of the lesson on routers. var GalleryRouter = Backbone.Router.extend({ /* define the route and function maps for this router */ Routers | 25
  • 40.
    routes: { "about" :"showAbout", /*Sample usage: http://unicorns.com/#about*/ "photos/:id" : "getPhoto", /*This is an example of using a ":param" variable which allows us to match any of the components between two URL slashes*/ /*Sample usage: http://unicorns.com/#photos/5*/ "search/:query" : "searchPhotos", /*We can also define multiple routes that are bound to the same map function, in this case searchPhotos(). Note below how we're optionally passing in a reference to a page number if one is supplied*/ /*Sample usage: http://unicorns.com/#search/lolcats*/ "search/:query/p:page" : "searchPhotos", /*As we can see, URLs may contain as many ":param"s as we wish*/ /*Sample usage: http://unicorns.com/#search/lolcats/p1*/ "photos/:id/download/*imagePath" : "downloadPhoto", /*This is an example of using a *splat. splats are able to match any number of URL components and can be combined with ":param"s*/ /*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/ /*If you wish to use splats for anything beyond default routing, it's probably a good idea to leave them at the end of a URL otherwise you may need to apply regular expression parsing on your fragment*/ "*other" : "defaultRoute" /*This is a default route that also uses a *splat. Consider the default route a wildcard for URLs that are either not matched or where the user has incorrectly typed in a route path manually*/ /*Sample usage: http://unicorns.com/#anything*/ }, showAbout: function(){ }, getPhoto: function(id){ /* Note that the id matched in the above route will be passed to this function */ console.log("You are trying to reach photo " + id); }, searchPhotos: function(query, page){ var page_number = page || 1; console.log("Page number: " + page_number + " of the results for " + query); }, downloadPhoto: function(id, path){ }, defaultRoute: function(other){ 26 | Chapter 2: The Basics
  • 41.
    console.log("Invalid. You attemptedto reach:" + other); } }); /* Now that we have a router setup, remember to instantiate it*/ var myGalleryRouter = new GalleryRouter(); As of Backbone 0.5+, it’s possible to opt-in for HTML5 pushState support via win dow.history.pushState. This permits you to define routes such as http://www.script- junkie.com/just/an/example. This will be supported with automatic degradation when a user’s browser doesn’t support pushState. For the purposes of this tutorial, we’ll use the hashtag method. Backbone.history Next, we need to initialize Backbone.history as it handles hashchange events in our application. This will automatically handle routes that have been defined and trigger callbacks when they’ve been accessed. The Backbone.history.start() method will simply tell Backbone that it’s OK to begin monitoring all hashchange events as follows: Backbone.history.start(); Router.navigate(); As an aside, if you would like to save application state to the URL at a particular point you can use the .navigate() method to achieve this. It simply updates your URL frag- ment without the need to trigger the hashchange event: /*Lets imagine we would like a specific fragment for when a user zooms into a photo*/ zoomPhoto: function(factor){ this.zoom(factor); //imagine this zooms into the image this.navigate("zoom/" + factor); //updates the fragment for us, but doesn't trigger the route } It is also possible for Router.navigate() to trigger the route as well as updating the URL fragment. zoomPhoto: function(factor){ this.zoom(factor); //imagine this zooms into the image this.navigate("zoom/" + factor, true); //updates the fragment for us and triggers the route } Namespacing When learning how to use Backbone, an important and commonly overlooked area by tutorials is namespacing. If you already have experience with namespacing in Java- Script, the following section will provide some advice on how to specifically apply concepts you know to Backbone, however I will also be covering explanations for be- ginners to ensure everyone is on the same page. Namespacing | 27
  • 42.
    What is namespacing? Thebasic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They’re important as it’s best to safeguard your code from breaking in the event of another script on the page using the same variable names as you are. As a good “citizen” of the global namespace, it’s also imperative that you do your best to similarly not prevent other developer’s scripts executing due to the same issues. JavaScript doesn’t really have built-in support for namespaces like other languages, however it does have closures which can be used to achieve a similar effect. In this section we’ll be taking a look shortly at some examples of how you can name- spaceyourmodels,views,routersandothercomponentsspecifically.Thepatternswe’ll be examining are: • Single global variables • Object Literals • Nested namespacing Single global variables One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below: var myApplication = (function(){ function(){ // ... }, return { // ... } })(); You’ve probably seen this technique before. A Backbone-specific example might look like this: var myViews = (function(){ return { PhotoView: Backbone.View.extend({ .. }), GalleryView: Backbone.View.extend({ .. }), AboutView: Backbone.View.extend({ .. }); //etc. }; })(); Here we can return a set of views, but the same technique could return an entire col- lection of models, views and routers depending on how you decide to structure your application. Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page. 28 | Chapter 2: The Basics
  • 43.
    One solution tothis problem, as mentioned by Peter Michaux, is to use prefix name- spacing. It’s a simple concept at heart, but the idea is you select a common prefix name (in this example, myApplication_) and then define any methods, variables or other ob- jects after the prefix. var myApplication_photoView = Backbone.View.extend({}), myApplication_galleryView = Backbone.View.extend({}); This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow. For more on Peter’s views about the single global variable pattern, read his excellent post on them. Note: There are several other variations on the single global variable pattern out in the wild, however having reviewed quite a few, I felt the prefixing approach applied best to Backbone. Object Literals Object Literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They’re beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, Object Literals often also take into account tests for the existence of a variable by the same name, which helps reduce the chances of collision. This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2. /*Doesn't check for existence of myApplication*/ var myApplication = {}; /* Does check for existence. If already defined, we use that instance. Option 1: if(!myApplication) myApplication = {}; Option 2: var myApplication = myApplication || {}; We can then populate our object literal to support models, views and collections (or any data, really): */ var myApplication = { models : {}, views : { pages : {} }, collections : {} }; One can also opt for adding properties directly to the namespace (such as your views, in the following example): Namespacing | 29
  • 44.
    var myGalleryViews =myGalleryViews || {}; myGalleryViews.photoView = Backbone.View.extend({}); myGalleryViews.galleryView = Backbone.View.extend({}); The benefit of this pattern is that you’re able to easily encapsulate all of your models, views, routers etc. in a way that clearly separates them and provides a solid foundation for extending your code. This pattern has a number of benefits. It’s often a good idea to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter it. Here’s an example of a hypothetical object literal that stores application configuration settings: var myConfig = { language: 'english', defaults: { enableGeolocation: true, enableSharing: false, maxPhotos: 20 }, theme: { skin: 'a', toolbars: { index: 'ui-navigation-toolbar', pages: 'ui-custom-toolbar' } } } Note that there are really only minor syntactical differences between the Object Literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g. for simpler storage when sending to the back-end), feel free to. For more on the Object Literal pattern, I recommend reading Rebecca Murphey’s excellent article on the topic. Nested namespacing An extension of the Object Literal pattern is nested namespacing. It’s another common pattern used that offers a lower risk of collision due to the fact that even if a top-level namespace already exists, it’s unlikely the same nested children do. For example, Ya- hoo’s YUI uses the nested object namespacing pattern extensively: YAHOO.util.Dom.getElementsByClassName('test'); Yahoo’s YUI uses the nested object namespacing pattern regularly and even Docu- mentCloud(thecreatorsofBackbone)usethenestednamespacingpatternintheirmain applications. A sample implementation of nested namespacing with Backbone may look like this: var galleryApp = galleryApp || {}; // perform similar check for nested children 30 | Chapter 2: The Basics
  • 45.
    galleryApp.routers = galleryApp.routers|| {}; galleryApp.model = galleryApp.model || {}; galleryApp.model.special = galleryApp.model.special || {}; // routers galleryApp.routers.Workspace = Backbone.Router.extend({}); galleryApp.routers.PhotoSearch = Backbone.Router.extend({}); // models galleryApp.model.Photo = Backbone.Model.extend({}); galleryApp.model.Comment = Backbone.Model.extend({}); // special models galleryApp.model.special.Admin = Backbone.Model.extend({}); This is readable, clearly organized, and is a relatively safe way of namespacing your Backbone application. The only real caveat however is that it requires your browser’s JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you’re calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the “nes- ted” approach to be quite negligible. Recommendation Reviewing the namespace patterns above, the option that I prefer when writing Back- bone applications is nested object namespacing with the object literal pattern. Single global variables may work fine for applications that are relatively trivial. How- ever, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that’s both readable and scalable. I feel this pattern achieves both of these objectives and is a good choice for most Backbone development. Additional Tips Automated Backbone Scaffolding Scaffolding can assist in expediting how quickly you can begin a new application by creating the basic files required for a project automatically. If you enjoy the idea of automated MVC scaffolding using Backbone, I’m happy to recommend checking out a tool called Brunch. It works very well with Backbone, Underscore, jQuery and CoffeeScript and is even used by companies such as Red Bull and Jim Beam. You may have to update any third party dependencies (e.g. latest jQuery or Zepto) when using it, but other than that it should be fairly stable to use right out of the box. Brunch can be installed via the nodejs package manager and is easy to get started with. If you happen to use Vim or Textmate as your editor of choice, you’ll be happy to know that there are Brunch bundles available for both. Additional Tips | 31
  • 46.
    Is there alimit to the number of routers I should be using? Andrew de Andrade has pointed out that DocumentCloud themselves usually only use a single router in most of their applications. You’re very likely to not require more than one or two routers in your own projects as the majority of your application routing can be kept organized in a single controller without it getting unwieldy. Is Backbone too small for my application’s needs? If you find yourself unsure of whether or not your application is too large to use Back- bone, I recommend reading my post on building large-scale jQuery & JavaScript ap- plications or reviewing my slides on client-side MVC architecture options. In both, I cover alternative solutions and my thoughts on the suitability of current MVC solutions for scaled application development. Backbone can be used for building both trivial and complex applications as demon- strated by the many examples Ashkenas has been referencing in the Backbone docu- mentation. As with any MVC framework however, it’s important to dedicate time to- wards planning out what models and views your application really needs. Diving straight into development without doing this can result in either spaghetti code or a large refactor later on and it’s best to avoid this where possible. At the end of the day, the key to building large applications is not to build large appli- cations in the first place. If you however find Backbone doesn’t cut it for your require- ments I strongly recommend checking out JavaScriptMVC or SproutCore as these both offer a little more than Backbone out of the box. Dojo and Dojo Mobile may also be of interest as these have also been used to build significantly complex apps by other de- velopers. 32 | Chapter 2: The Basics
  • 47.
    CHAPTER 3 RESTful Applications BuildingRESTful applications with Backbone In this section of the book, we’re going to take a look at developing RESTful applica- tions using Backbone.js and modern technology stacks. When the data for your back- end is exposed through a purely RESTful API, tasks such as retrieving (GET), creating (POST), updating (PUT) and deleting (DELETE) models are made easy through Back- bone’s Model API. This API is so intuitive in fact that switching from storing records in a local data-store (e.g localStorage) to a database/noSQL data-store is a lot simpler than you may think. Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB The first stack we’ll be looking at is: • Node.js • Express • Mongoose • and MongoDB with Jade used optionally as a view/templating engine. Reviewing the stack As you may know, node.js is an event-driven platform (built on the V8 runtime), de- signed for writing fast, scalable network applications. It’s reasonably lightweight, effi- cient and great for real-time applications that are data-intensive. 33
  • 48.
    Express is asmall web-development framework written with node.js, based on Sina- tra. It supports a number of useful features such as intuitive views, robust routing and a focus on high performance. Next on the list are MongoDB and Mongoose. MongoDB is an open-source, document- oriented database store designed with scalability and agility in mind. As a noSQL da- tabase, rather than storing data in tables and rows (something we’re very used to doing with relational databases), with MongoDB we instead store JSON-like documents us- ing dynamic schemas. One of the goals of Mongo is to try bridging the gap between key-value stores (speed, scalability) and relational databases (rich functionality). Mongoose is a JavaScript library that simplifies how we interact with Mongo. Like Express, it’s designed to work within the node.js environment and tries to solve some of the complexities with asynchronous data storage by offering a more user-friendly API. It also adds chaining features into the mix, allowing for a slightly more expressive way of dealing with our data. Jade is a template engine influenced by Haml (which we’ll be looking at later). It’s implemented with JavaScript (and also runs under node). In addition to supporting Express out of the box, it boasts a number of useful features including support for mixins, includes, caching, template inheritance and much more. Whilst abstractions like Jade certainly aren’t for everyone, our practical will cover working both with and without it. Practical For this practical, we’re going to once again look at extending the popular Backbone Todo application. Rather than relying on localStorage for data persistence, we’re going to switch to storing Todos in a MongoDB document-store instead. The code for this practical can be found in practicalsstacksoption2 app.js (See here for the source) We must first include the node dependencies required by our application. These are Express, Mongoose and Path (a module containing utilities for dealing with file paths. var application_root = __dirname, express = require("express"), path = require("path"), mongoose = require('mongoose'); Next, create a new Express server. express.createServer() is a simple way of creating an instance of express.HTTPServer, which we’ll be using to pass in our routes. var app = express.createServer(); After this, connect Mongoose up to a database (in our case, localhost should suffice). Should you require the ability to pass in authentication information, here’s a sample 34 | Chapter 3: RESTful Applications
  • 49.
    containing all ofthe supported URL parameters: mongodb://[username:pass word@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] mongoose.connect('mongodb://localhost/my_database'); A Mongoose model for any Todo item can now be easily defined by passing a schema instance to mongoose.model. In our case the schema covers a Todo item’s text content, its done state and order position in the overall Todo list. var Todo = mongoose.model('Todo', new mongoose.Schema({ text: String, done: Boolean, order: Number })); The configure() methods allows us to setup what we need for the current environment with our Express server. Note that lower down in the configuration are two view/view related lines. The last one explicitly sets the viewing/templating engine to be used as Jade app.set('view engine', 'jade'). We can avoid these if we wish to use plain HTML/JS for our templates instead. app.configure(function(){ // the bodyParser middleware parses JSON request bodies app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(application_root, "public"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.set('views', path.join(application_root, "views")); app.set('view engine', 'jade') }); Should you prefer to switch out Jade for an alternative view engine, this can be done fairly trivially. See the section under “Templating” here: https://github.com/joyent/ node/wiki/modules. For example, to switch to EJS, you would simply write app.set('view engine', 'ejs') Express makes use of common HTTP verbs (get, put, post etc.) to provide easy to use, expressive routing API based on CRUD (Create, Read, Update and Delete). Below for example, we can define what happens when the browser requests the root “/”. As a trivial route in this application, it doesn’t do anything particularly exciting, however getters typically read or retrieve data. app.get('/', function(req, res){ res.send('Hello World'); }); Onto something a little more useful and in our next route, navigating to “/todo” will actually render our Jade view “todo.jade”, as seen in the callback. Additional config- uration values can be passed as the second parameter, such as the custom title specified below. Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB | 35
  • 50.
    app.get('/todo', function(req, res){ res.render('todo',{title: "Our sample application"}); }); Next, we can see the first of our “/api/” routes. app.get('/api/todos', function(req, res){ return Todo.find(function(err, todos) { return res.send(todos); }); }); The callback to our next route supports querying for todos based on a specific ID. The route string itself (once compiled) will be converted from “/api/todos/:id” to a regular expression. As you might have guessed, this is a hint that routes can also be regular expression literals if we wished to do something more complex. app.get('/api/todos/:id', function(req, res){ return Todo.findById(req.params.id, function(err, todo) { if (!err) { return res.send(todo); } }); }); Similarly, we want to support updating todos based on a specific ID as well. The fol- lowing allows us to query a todo by ID and then update the values of it’s three attributes (text, done, order) easily. app.put('/api/todos/:id', function(req, res){ return Todo.findById(req.params.id, function(err, todo) { todo.text = req.body.text; todo.done = req.body.done; todo.order = req.body.order; return todo.save(function(err) { if (!err) { console.log("updated"); } return res.send(todo); }); }); }); We’ve so far covered requesting todos and updating them, but a core part of the ap- plication requires us to insert (or add) new todos to our data-store. Below we can create new Todo models and simply save them. app.post('/api/todos', function(req, res){ var todo; todo = new Todo({ text: req.body.text, done: req.body.done, order: req.body.order }); todo.save(function(err) { if (!err) { 36 | Chapter 3: RESTful Applications
  • 51.
    Another Random ScribdDocument with Unrelated Content
  • 52.
    leading division, soas to be ready for battle. Sitting on his horse by the road-side, while the deployment was making, he saw a man coming down the road, riding as hard as he could, and as he approached he recognized him as one of his own "foragers," mounted on a white horse, with a rope bridle and a blanket for saddle. As he came near he called out, "Hurry up, general; we have got the railroad!" So, while we, the generals, were proceeding deliberately to prepare for a serious battle, a parcel of our foragers, in search of plunder, had got ahead and actually captured the South Carolina Railroad, a line of vital importance to the rebel Government. As soon as we struck the railroad, details of men were set to work to tear up the rails, to burn the ties and twist the bars. This was a most important railroad, and I proposed to destroy it completely for fifty miles, partly to prevent a possibility of its restoration and partly to utilize the time necessary for General Slocum to get up. The country thereabouts was very poor, but the inhabitants mostly remained at home. Indeed, they knew not where to go. The enemy's cavalry had retreated before us, but his infantry was reported in some strength at Branchville, on the farther side of the Edisto; yet on the appearance of a mere squad of our men they burned their own bridges the very thing I wanted, for we had no use for them, and they had. We all remained strung along this railroad till the 9th of February-- the Seventeenth Corps on the right, then the Fifteenth, Twentieth, and cavalry, at Blackville. General Slocum reached Blackville that day, with Geary's division of the Twentieth Corps, and reported the Fourteenth Corps (General Jeff. C. Davis's) to be following by way of Barnwell. On the 10th I rode up to Blackville, where I conferred with Generals Slocum and Kilpatrick, became satisfied that the whole army would be ready within a day, and accordingly made orders for the next movement north to Columbia, the right wing to strike Orangeburg en route. Kilpatrick was ordered to demonstrate strongly toward Aiken, to keep up the delusion that we might turn to Augusta; but he was notified that Columbia was the next objective, and that he should cover the left flank against Wheeler, who hung
  • 53.
    around it. Iwanted to reach Columbia before any part of Hood's army could possibly get there. Some of them were reported as having reached Augusta, under the command of General Dick Taylor. Having sufficiently damaged the railroad, and effected the junction of the entire army, the general march was resumed on the 11th, each corps crossing the South Edisto by separate bridges, with orders to pause on the road leading from Orangeberg to Augusta, till it was certain that the Seventeenth Corps had got possession of Orangeburg. This place was simply important as its occupation would sever the communications between Charleston and Columbia. All the heads of column reached this road, known as the Edgefield road, during the 12th, and the Seventeenth Corps turned to the right, against Orangeburg. When I reached the head of column opposite Orangeburg, I found Giles A. Smith's division halted, with a battery unlimbered, exchanging shots with a party on the opposite side of the Edisto. He reported that the bridge was gone, and that the river was deep and impassable. I then directed General Blair to send a strong division below the town, some four or five miles, to effect a crossing there. He laid his pontoon-bridge, but the bottom on the other side was overflowed, and the men had to wade through it, in places as deep as their waists. I was with this division at the time, on foot, trying to pick my way across the overflowed bottom; but, as soon as the head of column reached the sand-hills, I knew that the enemy would not long remain in Orangeburg, and accordingly returned to my horse, on the west bank, and rode rapidly up to where I had left Giles A. Smith. I found him in possession of the broken bridge, abreast of the town, which he was repairing, and I was among the first to cross over and enter the town. By and before the time either Force's or Giles A. Smith's skirmishers entered the place, several stores were on fire, and I am sure that some of the towns-people told me that a Jew merchant had set fire to his own cotton and store, and from this the fire had spread. This, however, was soon put out, and the Seventeenth Corps (General Blair) occupied the place during that night. I remember to have visited a large hospital, on the hill near the railroad depot,
  • 54.
    which was occupiedby the orphan children who had been removed from the asylum in Charleston. We gave them protection, and, I think, some provisions. The railroad and depot were destroyed by order, and no doubt a good deal of cotton was burned, for we all regarded cotton as hostile property, a thing to be destroyed. General Blair was ordered to break up this railroad, forward to the point where it crossed the Santee, and then to turn for Columbia. On the morning of the 13th I again joined the Fifteenth Corps, which crossed the North Edisto by Snilling's Bridge, and moved straight for Columbia, around the head of Caw-Caw Swamp. Orders were sent to all the columns to turn for Columbia, where it was supposed the enemy had concentrated all the men they could from Charleston, Augusta, and even from Virginia. That night I was with the Fifteenth Corps, twenty-one miles from Columbia, where my aide, Colonel Audenried, picked up a rebel officer on the road, who, supposing him to be of the same service with himself, answered all his questions frankly, and revealed the truth that there was nothing in Columbia except Hampton's cavalry. The fact was, that General Hardee, in Charleston, took it for granted that we were after Charleston; the rebel troops in Augusta supposed they were "our objective;" so they abandoned poor Columbia to the care of Hampton's cavalry, which was confused by the rumors that poured in on it, so that both Beauregard and Wade Hampton, who were in Columbia, seem to have lost their heads. On the 14th the head of the Fifteenth Corps, Charles R. Woods's division, approached the Little Congaree, a broad, deep stream, tributary to the Main Congaree; six or eight miles below Columbia. On the opposite side of this stream was a newly-constructed fort, and on our side--a wide extent of old cotton-fields, which, had been overflowed, and was covered with a deep slime. General Woods had deployed his leading brigade, which was skirmishing forward, but he reported that the bridge was gone, and that a considerable force of the enemy was on the other side. I directed General Howard or Logan to send a brigade by a circuit to the left, to see if this stream could not be crossed higher up, but at the same time knew that
  • 55.
    General Slocum's routeworld bring him to Colombia behind this stream, and that his approach would uncover it. Therefore, there was no need of exposing much life. The brigade, however, found means to cross the Little Congaree, and thus uncovered the passage by the main road, so that General Woods's skirmishers at once passed over, and a party was set to work to repair the bridge, which occupied less than an hour, when I passed over with my whole staff. I found the new fort unfinished and unoccupied, but from its parapet could see over some old fields bounded to the north and west by hills skirted with timber. There was a plantation to our left, about half a mile, and on the edge of the timber was drawn up a force of rebel cavalry of about a regiment, which advanced, and charged upon some, of our foragers, who were plundering the plantation; my aide, Colonel Audenried, who had ridden forward, came back somewhat hurt and bruised, for, observing this charge of cavalry, he had turned for us, and his horse fell with him in attempting to leap a ditch. General Woods's skirmish-line met this charge of cavalry, and drove it back into the woods and beyond. We remained on that ground during the night of the 15th, and I camped on the nearest dry ground behind the Little Congaree, where on the next morning were made the written' orders for the government of the troops while occupying Columbia. These are dated February 16, 1865, in these words: General Howard will cross the Saluda and Broad Rivers as near their mouths as possible, occupy Columbia, destroy the public buildings, railroad property, manufacturing and machine shops; but will spare libraries, asylums, and private dwellings. He will then move to Winnsboro', destroying en route utterly that section of the railroad. He will also cause all bridges, trestles, water-tanks, and depots on the railroad back to the Wateree to be burned, switches broken, and such other destruction as he can find time to accomplish consistent with proper celerity. These instructions were embraced in General Order No. 26, which prescribed the routes of march for the several columns as far as Fayetteville, North Carolina, and is conclusive that I then regarded
  • 56.
    Columbia as simplyone point on our general route of march, and not as an important conquest. During the 16th of February the Fifteenth Corps reached the point opposite Columbia, and pushed on for the Saluda Factory three miles above, crossed that stream, and the head of column reached Broad River just in time to find its bridge in flames, Butler's cavalry having just passed over into Columbia. The head of Slocum's column also reached the point opposite Columbia the same morning, but the bulk of his army was back at Lexington. I reached this place early in the morning of the 16th, met General Slocum there; and explained to him the purport of General Order No. 26, which contemplated the passage of his army across Broad River at Alston, fifteen miles above Columbia. Riding down to the river-bank, I saw the wreck of the large bridge which had been burned by the enemy, with its many stone piers still standing, but the superstructure gone. Across the Congaree River lay the city of Columbia, in plain, easy view. I could see the unfinished State-House, a handsome granite structure, and the ruins of the railroad depot, which were still smouldering. Occasionally a few citizens or cavalry could be seen running across the streets, and quite a number of negroes were seemingly busy in carrying off bags of grain or meal, which were piled up near the burned depot. Captain De Gres had a section of his twenty-pound Parrott guns unlimbered, firing into the town. I asked him what he was firing for; he said he could see some rebel cavalry occasionally at the intersections of the streets, and he had an idea that there was a large force of infantry concealed on the opposite bank, lying low, in case we should attempt to cross over directly into the town. I instructed him not to fire any more into the town, but consented to his bursting a few shells near the depot, to scare away the negroes who were appropriating the bags of corn and meal which we wanted, also to fire three shots at the unoccupied State-House. I stood by and saw these fired, and then all firing ceased. Although this matter of firing into Columbia has been the subject of much abuse and investigation, I have yet to hear of any single person
  • 57.
    having been killedin Columbia by our cannon. On the other hand, the night before, when Woods's division was in camp in the open fields at Little Congaree, it was shelled all night by a rebel battery from the other aide of the river. This provoked me much at the time, for it was wanton mischief, as Generals Beauregard and Hampton must have been convinced that they could not prevent our entrance into Columbia. I have always contended that I would have been justified in retaliating for this unnecessary act of war, but did not, though I always characterized it as it deserved. The night of the 16th I camped near an old prison bivouac opposite Columbia, known to our prisoners of war as "Camp Sorghum," where remained the mud-hovels and holes in the ground which our prisoners had made to shelter themselves from the winter's cold and the summer's heat. The Fifteenth Corps was then ahead, reaching to Broad River, about four miles above Columbia; the Seventeenth Corps was behind, on the river-bank opposite Columbia; and the left wing and cavalry had turned north toward Alston. The next morning, viz., February 17th, I rode to the head of General Howard's column, and found that during the night he had ferried Stone's brigade of Woods's division of the Fifteenth Corps across by rafts made of the pontoons, and that brigade was then deployed on the opposite bank to cover the construction of a pontoon-bridge nearly finished. I sat with General Howard on a log, watching the men lay this bridge; and about 9 or 10 A.M. a messenger came from Colonel Stone on the other aide, saying that the Mayor of Columbia had come out of the city to surrender the place, and asking for orders. I simply remarked to General Howard that he had his orders, to let Colonel Stone go on into the city, and that we would follow as soon as the bridge was ready. By this same messenger I received a note in pencil from the Lady Superioress of a convent or school in Columbia, in which she claimed to have been a teacher in a convent in Brown County, Ohio, at the time my daughter Minnie was a pupil there, and therefore asking special protection. My recollection is,
  • 58.
    that I gavethe note to my brother-in-law, Colonel Ewing, then inspector-general on my staff, with instructions to see this lady, and assure her that we contemplated no destruction of any private property in Columbia at all. As soon as the bridge was done, I led my horse over it, followed by my whole staff. General Howard accompanied me with his, and General Logan was next in order, followed by General C. R. Woods, and the whole of the Fifteenth Corps. Ascending the hill, we soon emerged into a broad road leading into Columbia, between old fields of corn and cotton, and, entering the city, we found seemingly all its population, white and black, in the streets. A high and boisterous wind was prevailing from the north, and flakes of cotton were flying about in the air and lodging in the limbs of the trees, reminding us of a Northern snow-storm. Near the market-square we found Stone's brigade halted, with arms stacked, and a large detail of his men, along with some citizens, engaged with an old fire-engine, trying to put out the fire in a long pile of burning cotton-bales, which I was told had been fired by the rebel cavalry on withdrawing from the city that morning. I know that, to avoid this row of burning cotton-bales, I had to ride my horse on the sidewalk. In the market-square had collected a large crowd of whites and blacks, among whom was the mayor of the city, Dr. Goodwin, quite a respectable old gentleman, who was extremely anxious to protect the interests of the citizens. He was on foot, and I on horseback, and it is probable I told him then not to be uneasy, that we did not intend to stay long, and had no purpose to injure the private citizens or private property. About this time I noticed several men trying to get through the crowd to speak with me, and called to some black people to make room for them; when they reached me, they explained that they were officers of our army, who had been prisoners, had escaped from the rebel prison and guard, and were of course overjoyed to find themselves safe with us. I told them that, as soon as things settled down, they should report to General Howard, who would provide for their safety, and enable them to travel with us. One of them handed me a paper, asking me to read it at my leisure; I put it in my breast-pocket and
  • 59.
    rode on. GeneralHoward was still with me, and, riding down the street which led by the right to the Charleston depot, we found it and a large storehouse burned to the ground, but there were, on the platform and ground near by, piles of cotton bags filled with corn and corn-meal, partially burned. A detachment of Stone's brigade was guarding this, and separating the good from the bad. We rode along the railroad-track, some three or four hundred yards, to a large foundery, when some man rode up and said the rebel cavalry were close by, and he warned us that we might get shot. We accordingly turned back to the market-square, and en route noticed that, several of the men were evidently in liquor, when I called General Howard's attention to it. He left me and rode toward General Woods's head of column, which was defiling through the town. On reaching the market- square, I again met Dr. Goodwin, and inquired where he proposed to quarter me, and he said that he had selected the house of Blanton Duncan, Esq., a citizen of Louisville, Kentucky, then a resident there, who had the contract for manufacturing the Confederate money, and had fled with Hampton's cavalry. We all rode some six or eight squares back from the new State-House, and found a very good modern house, completely furnished, with stabling and a large yard, took it as our headquarters, and occupied it during our stay. I considered General Howard as in command of the place, and referred the many applicants for guards and protection to him. Before our headquarters-wagons had got up, I strolled through the streets of Columbia, found sentinels posted at the principal intersections, and generally good order prevailing, but did not again return to the main street, because it was filled with a crowd of citizens watching the soldiers marching by. During the afternoon of that day, February 17th, the whole of the Fifteenth Corps passed through the town and out on the Camden and Winnsboro' roads. The Seventeenth Corps did not enter the city at all, but crossed directly over to the Winnsboro' road from the pontoon bridge at Broad River, which was about four miles above the city.
  • 60.
    After we hadgot, as it were, settled in Blanton Duncan's house, say about 2 p.m., I overhauled my pocket according to custom, to read more carefully the various notes and memoranda received during the day, and found the paper which had been given me, as described, by one of our escaped prisoners. It proved to be the song of "Sherman's March to the Sea," which had been composed by Adjutant S. H. M. Byers, of the Fifth Iowa Infantry, when a prisoner in the asylum at Columbia, which had been beautifully written off by a fellow-prisoner, and handed to me in person. This appeared to me so good that I at once sent for Byers, attached him to my staff, provided him with horse and equipment, and took him as far as Fayetteville, North Carolina, whence he was sent to Washington as bearer of dispatches. He is now United States consul at Zurich, Switzerland, where I have since been his guest. I insert the song here for convenient reference and preservation. Byers said that there was an excellent glee-club among the prisoners in Columbia, who used to sing it well, with an audience often of rebel ladies: SHERMAN'S MARCH TO THE SEA. Composed by Adjutant Byers, Fifth Iowa Infantry. Arranged and sung by the Prisoners in Columbia Prison. I Our camp-fires shone bright on the mountain That frowned on the river below, As we stood by our guns in the morning, And eagerly watched for the foe; When a rider came out of the darkness That hung over mountain and tree, And shouted, "Boys, up and be ready! For Sherman will march to the sea!"
  • 61.
    CHORUS: Then sang wea song of our chieftain, That echoed over river and lea; And the stars of our banner shone brighter When Sherman marched down to the sea! II Then cheer upon cheer for bold Sherman Went up from each valley and glen, And the bugles reechoed the music That came from the lips of the men; For we knew that the stars in our banner More bright in their splendor would be, And that blessings from Northland world greet us, When Sherman marched down to the sea! Then sang we a song, etc. III Then forward, boys! forward to battle! We marched on our wearisome way, We stormed the wild hills of Resacar God bless those who fell on that day! Then Kenesaw frowned in its glory, Frowned down on the flag of the free; But the East and the West bore our standard, And Sherman marched on to the sea! Then sang we a song, etc. IV
  • 62.
    Still onward wepressed, till our banners Swept out from Atlanta's grim walls, And the blood of the patriot dampened The soil where the traitor-flag falls; But we paused not to weep for the fallen, Who slept by each river and tree, Yet we twined them a wreath of the laurel, As Sherman marched down to the sea! Then sang we a song, etc. V Oh, proud was our army that morning, That stood where the pine darkly towers, When Sherman said, "Boys, you are weary, But to-day fair Savannah is ours!" Then sang we the song of our chieftain, That echoed over river and lea, And the stars in our banner shone brighter When Sherman camped down by the sea! Toward evening of February 17th, the mayor, Dr. Goodwin, came to my quarters at Duncan's house, and remarked that there was a lady in Columbia who professed to be a special friend of mine. On his giving her name, I could not recall it, but inquired as to her maiden or family name. He answered Poyas. It so happened that, when I was a lieutenant at Fort Moultrie, in 1842-'46, I used very often to visit a family of that name on the east branch of Cooper River, about forty miles from Fort Moultrie, and to hunt with the son, Mr. James Poyas, an elegant young fellow and a fine sportsman. His father, mother, and several sisters, composed the family, and were
  • 63.
    extremely hospitable. Oneof the ladies was very fond of painting in water-colors, which was one of my weaknesses, and on one occasion I had presented her with a volume treating of water-colors. Of course, I was glad to renew the acquaintance, and proposed to Dr. Goodwin that we should walk to her house and visit this lady, which we did. The house stood beyond the Charlotte depot, in a large lot, was of frame, with a high porch, which was reached by a set of steps outside. Entering this yard, I noticed ducks and chickens, and a general air of peace and comfort that was really pleasant to behold at that time of universal desolation; the lady in question met us at the head of the steps and invited us into a parlor which was perfectly neat and well furnished. After inquiring about her father, mother, sisters, and especially her brother James, my special friend, I could not help saying that I was pleased to notice that our men had not handled her house and premises as roughly as was their wont. "I owe it to you, general," she answered. "Not at all. I did not know you were here till a few minutes ago." She reiterated that she was indebted to me for the perfect safety of her house and property, and added, "You remember, when you were at our house on Cooper River in 1845, you gave me a book;" and she handed me the book in question, on the fly leaf of which was written: "To Miss Poyas, with the compliments of W. T. Sherman, First-lieutenant Third Artillery." She then explained that, as our army approached Columbia, there was a doubt in her mind whether the terrible Sherman who was devastating the land were W. T. Sherman or T. W. Sherman, both known to be generals in the Northern army; but, on the supposition that he was her old acquaintance, when Wade Hampton's cavalry drew out of the city, calling out that the Yankees were coming, she armed herself with this book, and awaited the crisis. Soon the shouts about the markethouse announced that the Yankees had come; very soon men were seen running up and down the streets; a parcel of them poured over the fence, began to chase the chickens and ducks, and to enter her house. She observed one large man, with full beard, who exercised some authority, and to him she appealed in the name of "his general." "What do you know of Uncle Billy?" "Why," she said, "when he was a young man he used to
  • 64.
    be our friendin Charleston, and here is a book he gave me." The officer or soldier took the book, looked at the inscription, and, turning to his fellows, said: "Boys, that's so; that's Uncle Billy's writing, for I have seen it often before." He at once commanded the party to stop pillaging, and left a man in charge of the house, to protect her until the regular provost-guard should be established. I then asked her if the regular guard or sentinel had been as good to her. She assured me that he was a very nice young man; that he had been telling her all about his family in Iowa; and that at that very instant of time he was in another room minding her baby. Now, this lady had good sense and tact, and had thus turned aside a party who, in five minutes more, would have rifled her premises of all that was good to eat or wear. I made her a long social visit, and, before leaving Columbia, gave her a half-tierce of rice and about one hundred pounds of ham from our own mess-stores. In like manner, that same evening I found in Mrs. Simons another acquaintance--the wife of the brother of Hon. James Simons, of Charleston, who had been Miss Wragg. When Columbia was on fire that night, and her house in danger, I had her family and effects carried to my own headquarters, gave them my own room and bed, and, on leaving Columbia the next day, supplied her with a half- barrel of hams and a half-tierce of rice. I mention these specific facts to show that, personally, I had no malice or desire to destroy that city or its inhabitants, as is generally believed at the South. Having walked over much of the suburbs of Columbia in the afternoon, and being tired, I lay down on a bed in Blanton Duncan's house to rest. Soon after dark I became conscious that a bright light was shining on the walls; and, calling some one of my staff (Major Nichols, I think) to inquire the cause, he said there seemed to be a house on fire down about the market-house. The same high wind still prevailed, and, fearing the consequences, I bade him go in person to see if the provost-guard were doing its duty. He soon returned, and reported that the block of buildings directly opposite the burning cotton of that morning was on fire, and that it was spreading; but he had found General Woods on the ground, with
  • 65.
    plenty of mentrying to put the fire out, or, at least, to prevent its extension. The fire continued to increase, and the whole heavens became lurid. I dispatched messenger after messenger to Generals Howard, Logan, and Woods, and received from them repeated assurances that all was being done that could be done, but that the high wind was spreading the flames beyond all control. These general officers were on the ground all night, and Hazen's division had been brought into the city to assist Woods's division, already there. About eleven o'clock at night I went down-town myself, Colonel Dayton with me; we walked to Mr. Simons's house, from which I could see the flames rising high in the air, and could hear the roaring of the fire. I advised the ladies to move to my headquarters, had our own headquarter-wagons hitched up, and their effects carried there, as a place of greater safety. The whole air was full of sparks and of flying masses of cotton, shingles, etc., some of which were carried four or five blocks, and started new fires. The men seemed generally under good control, and certainly labored hard to girdle the fire, to prevent its spreading; but, so long as the high wind prevailed, it was simply beyond human possibility. Fortunately, about 3 or 4 a.m., the wind moderated, and gradually the fire was got under control; but it had burned out the very heart of the city, embracing several churches, the old State-House, and the school or asylum of that very Sister of Charity who had appealed for my personal protection. Nickerson's Hotel, in which several of my staff were quartered, was burned down, but the houses occupied by myself, Generals Howard and Logan, were not burned at all. Many of the people thought that this fire was deliberately planned and executed. This is not true. It was accidental, and in my judgment began with the cotton which General Hampton's men had set fire to on leaving the city (whether by his orders or not is not material), which fire was partially subdued early in the day by our men; but, when night came, the high wind fanned it again into full blaze, carried it against the frame houses, which caught like tinder, and soon spread beyond our control.
  • 66.
    This whole subjecthas since been thoroughly and judicially investigated, in some cotton cases, by the mixed commission on American and British claims, under the Treaty of Washington, which commission failed to award a verdict in favor of the English claimants, and thereby settled the fact that the destruction of property in Columbia, during that night, did not result from the acts of the General Government of the United States--that is to say, from my army. In my official report of this conflagration, I distinctly charged it to General Wade Hampton, and confess I did so pointedly, to shake the faith of his people in him, for he was in my opinion boastful, and professed to be the special champion of South Carolina.
  • 67.
    Full Size The morningsun of February 18th rose bright and clear over a ruined city. About half of it was in ashes and in smouldering heaps. Many of the people were houseless, and gathered in groups in the suburbs, or in the open parks and spaces, around their scanty piles of furniture. General Howard, in concert with the mayor, did all that was possible to provide other houses for them; and by my authority he turned over to the Sisters of Charity the Methodist College, and to the mayor five hundred beef-cattle; to help feed the people; I also gave the mayor (Dr. Goodwin) one hundred muskets, with which to arm a guard to maintain order after we should leave the neighborhood. During the 18th and 19th we remained in Columbia, General Howard's troops engaged in tearing up and destroying the railroad, back toward the Wateree, while a strong detail, under the immediate supervision of Colonel O. M. Poe, United States Engineers, destroyed the State Arsenal, which was found to be well supplied with shot, shell, and ammunition. These were hauled in wagons to the Saluda River, under the supervision of Colonel Baylor, chief of ordnance, and emptied into deep water, causing a very serious accident by the bursting of a percussion-shell, as it struck another on the margin of the water. The flame followed back a train of powder which had sifted out, reached the wagons, still partially loaded, and exploded them, killing sixteen men and destroying
  • 68.
    several wagons andteams of mules. We also destroyed several valuable founderies and the factory of Confederate money. The dies had been carried away, but about sixty handpresses remained. There was also found an immense quantity of money, in various stages of manufacture, which our men spent and gambled with in the most lavish manner. Having utterly ruined Columbia, the right wing began its march northward, toward Winnsboro', on the 20th, which we reached on the 21st, and found General Slocum, with the left wing, who had come by the way of Alston. Thence the right wing was turned eastward, toward Cheraw, and Fayetteville, North Carolina, to cross the Catawba River at Peay's Ferry. The cavalry was ordered to follow the railroad north as far as Chester, and then to turn east to Rocky Mount, the point indicated for the passage of the left wing. In person I reached Rocky Mount on the 22d, with the Twentieth Corps, which laid its pontoon-bridge and crossed over during the 23d. Kilpatrick arrived the next day, in the midst of heavy rain, and was instructed to cross the Catawba at once, by night, and to move up to Lancaster, to make believe we were bound for Charlotte, to which point I heard that Beauregard had directed all his detachments, including a corps of Hood's old army, which had been marching parallel with us, but had failed to make junction with, the forces immediately opposing us. Of course, I had no purpose of going to Charlotte, for the right wing was already moving rapidly toward Fayetteville, North Carolina. The rain was so heavy and persistent that the Catawba, River rose fast, and soon after I had crossed the pontoon bridge at Rocky Mount it was carried away, leaving General Davis, with the Fourteenth Corps, on the west bank. The roads were infamous, so I halted the Twentieth Corps at Hanging Rock for some days, to allow time for the Fourteenth to get over. General Davis had infinite difficulty in reconstructing his bridge, and was compelled to use the fifth chains of his wagons for anchor- chains, so that we were delayed nearly a week in that neighborhood. While in camp at Hanging Rock two prisoners were brought to me-- one a chaplain, the other a boy, son of Richard Bacot, of Charleston,
  • 69.
    whom I hadknown as a cadet at West Point. They were just from Charleston, and had been sent away by General Hardee in advance, because he was, they said, evacuating Charleston. Rumors to the same effect had reached me through the negroes, and it was, moreover, reported that Wilmington, North Carolina, was in possession of the Yankee troops; so that I had every reason to be satisfied that our march was fully reaping all the fruits we could possibly ask for. Charleston was, in fact, evacuated by General Hardee on the 18th of February, and was taken possession of by a brigade of General Fosters troops, commanded by General Schimmelpfennig, the same day. Hardee had availed himself of his only remaining railroad, by Florence to Cheraw; had sent there much of his ammunition and stores, and reached it with the effective part of the garrison in time to escape across the Pedee River before our arrival. Wilmington was captured by General Terry on the 22d of February; but of this important event we only knew by the vague rumors which reached us through rebel sources. General Jeff. C. Davis got across the Catawba during the 27th, and the general march was resumed on Cheraw. Kilpatrick remained near Lancaster, skirmishing with Wheeler's and Hampton's cavalry, keeping up the delusion that we proposed to move on Charlotte and Salisbury, but with orders to watch the progress of the Fourteenth Corps, and to act in concert with it, on its left rear. On the 1st of March I was at Finlay's Bridge across Lynch's Creek, the roads so bad that we had to corduroy nearly every foot of the way; but I was in communication with all parts of the army, which had met no serious opposition from the enemy. On the 2d of March we entered the village of Chesterfield, skirmishing with Butler's cavalry, which gave ground rapidly. There I received a message from General Howard, who, reported that he was already in Cheraw with the Seventeenth Corps, and that the Fifteenth was near at hand. General Hardee had retreated eastward across the Pedee, burning the bridge. I therefore directed the left wing to march for Sneedsboro', about ten miles above Cheraw, to cross the Pedee there, while I in person proposed to cross over and join the right
  • 70.
    wing in Cheraw.Early in the morning of the 3d of March I rode out of Chesterfield along with the Twentieth Corps, which filled the road, forded Thompson's Creek, and, at the top of the hill beyond, found a road branching off to the right, which corresponded with the one, on my map leading to Cheraw. Seeing a negro standing by the roadside, looking at the troops passing, I inquired of him what road that was. "Him lead to Cheraw, master!" "Is it a good road, and how far?" "A very good road, and eight or ten miles." "Any guerrillas?" "Oh! no, master, dey is gone two days ago; you could have played cards on der coat-tails, dey was in sich a hurry!" I was on my Lexington horse, who was very handsome and restive, so I made signal to my staff to follow, as I proposed to go without escort. I turned my horse down the road, and the rest of the staff followed. General Barry took up the questions about the road, and asked the same negro what he was doing there. He answered, "Dey say Massa Sherman will be along soon!" "Why," said General Barry, "that was General Sherman you were talking to." The poor negro, almost in the attitude of prayer, exclaimed: "De great God! just look at his horse!" He ran up and trotted by my side for a mile or so, and gave me all the information he possessed, but he seemed to admire the horse more than the rider. We reached Cheraw in a couple of hours in a drizzling rain, and, while waiting for our wagons to come up, I staid with General Blair in a large house, the property of a blockade-runner, whose family remained. General Howard occupied another house farther down- town. He had already ordered his pontoon-bridge to be laid across the Pedee, there a large, deep, navigable stream, and Mower's division was already across, skirmishing with the enemy about two miles out. Cheraw was found to be full of stores which had been sent up from Charleston prior to its evacuation, and which could not be removed. I was satisfied, from inquiries, that General Hardee had with him only the Charleston garrison, that the enemy had not divined our movements, and that consequently they were still scattered from Charlotte around to Florence, then behind us. Having thus secured the passage of the Pedee, I felt no uneasiness about
  • 71.
    the future, becausethere remained no further great impediment between us and Cape Fear River, which I felt assured was by that time in possession of our friends. The day was so wet that we all kept in-doors; and about noon General Blair invited us to take lunch with him. We passed down into the basement dining-room, where the regular family table was spread with an excellent meal; and during its progress I was asked to take some wine, which stood upon the table in venerable bottles. It was so very good that I inquired where it came from. General Blair simply asked, "Do you like it?" but I insisted upon knowing where he had got it; he only replied by asking if I liked it, and wanted some. He afterward sent to my bivouac a case containing a dozen bottles of the finest madeira I ever tasted; and I learned that he had captured, in Cheraw, the wine of some of the old aristocratic families of Charleston, who had sent it up to Cheraw for safety, and heard afterward that Blair had found about eight wagon-loads of this wine, which he distributed to the army generally, in very fair proportions. After finishing our lunch, as we passed out of the dining room, General Blair asked me, if I did not want some saddle-blankets, or a rug for my tent, and, leading me into the hall to a space under the stairway, he pointed out a pile of carpets which had also been sent up from Charleston for safety. After our headquarter-wagons got up, and our bivouac was established in a field near by, I sent my orderly (Walter) over to General Blair, and he came back staggering under a load of carpets, out of which the officers and escort made excellent tent-rugs, saddle-cloths, and blankets. There was an immense amount of stores in Cheraw, which were used or destroyed; among them twenty-four guns, two thousand muskets, and thirty-six hundred barrels of gunpowder. By the carelessness of a soldier, an immense pile of this powder was exploded, which shook the town badly; and killed and maimed several of our men. We remained in or near Cheraw till the 6th of March, by which time the army was mostly across the Pedee River, and was prepared to resume the march on Fayetteville. In a house where General Hardee had been, I found a late New York Tribune, of fully a month
  • 72.
    later date thanany I had seen. It contained a mass of news of great interest to us, and one short paragraph which I thought extremely mischievous. I think it was an editorial, to the effect that at last the editor had the satisfaction to inform his readers that General Sherman would next be heard from about Goldsboro', because his supply-vessels from Savannah were known to be rendezvousing at Morehead City:--Now, I knew that General Hardee had read that same paper, and that he would be perfectly able to draw his own inferences. Up to, that moment I had endeavored so to feign to our left that we had completely, misled our antagonists; but this was no longer possible, and I concluded that we must be ready, for the concentration in our front of all the force subject to General Jos. Johnston's orders, for I was there also informed that he had been restored to the full command of the Confederate forces in South and North Carolina. On the 6th of March I crossed the Pedee, and all the army marched for Fayetteville: the Seventeenth Corps kept well to the right, to make room; the Fifteenth Corps marched by a direct road; the Fourteenth Corps also followed a direct road from Sneedsboro', where it had crossed the Pedee; and the Twentieth Corps, which had come into Cheraw for the convenience of the pontoon-bridge, diverged to the left, so as to enter Fayetteville next after the Fourteenth Corps, which was appointed to lead into Fayetteville. Kilpatrick held his cavalry still farther to the left rear on the roads from Lancaster, by way of Wadesboro' and New Gilead, so as to cover our trains from Hampton's and Wheeler's cavalry, who had first retreated toward the north. I traveled with the Fifteenth Corps, and on the 8th of March reached Laurel Hill, North Carolina. Satisfied that our troops must be at Wilmington, I determined to send a message there; I called for my man, Corporal Pike, whom I had rescued as before described, at Columbia, who was then traveling with our escort, and instructed him in disguise to work his way to the Cape Fear River, secure a boat, and float down to Wilmington to convey a letter, and to report our approach. I also called on General Howard for another volunteer, and he brought me a very clever
  • 73.
    young sergeant, whois now a commissioned officer in the regular army. Each of these got off during the night by separate routes, bearing the following message, reduced to the same cipher we used in telegraphic messages: HEADQUARTERS MILITARY DIVISION OF THE MISSISSIPPI IN THE FIELD, LAUREL HILL, Wednesday, March 8, 1865. Commanding Officer, Wilmington, North Carolina: We are marching for Fayetteville, will be there Saturday, Sunday, and Monday, and will then march for Goldsboro'. If possible, send a boat up Cape Fear River, and have word conveyed to General Schofield that I expect to meet him about Goldsboro'. We are all well and have done finely. The rains make our roads difficult, and may delay us about Fayetteville, in which case I would like to have some bread, sugar, and coffee. We have abundance of all else. I expect to reach Goldsboro' by the 20th instant. W. T. SHERMAN, Major-General. On the 9th I was with the Fifteenth Corps, and toward evening reached a little church called Bethel, in the woods, in which we took refuge in a terrible storm of rain, which poured all night, making the roads awful. All the men were at work corduroying the roads, using
  • 74.
    fence-rails and splitsaplings, and every foot of the way had thus to be corduroyed to enable the artillery and wagons to pass. On the 10th we made some little progress; on the 11th I reached Fayetteville, and found that General Hardee, followed by Wade Hampton's cavalry, had barely escaped across Cape Fear River, burning the bridge which I had hoped to save. On reaching Fayetteville I found General Slocum already in possession with the Fourteenth Corps, and all the rest of the army was near at hand. A day or two before, General Kilpatrick, to our left rear, had divided his force into two parts, occupying roads behind the Twentieth Corps, interposing between our infantry columns and Wade Hampton's cavalry. The latter, doubtless to make junction with General Hardee, in Fayetteville, broke across this line, captured the house in which General Kilpatrick and the brigade-commander, General Spencer, were, and for a time held possession of the camp and artillery of the brigade. However, General Kilpatrick and most of his men escaped into a swamp with their arms, reorganized and returned, catching Hampton's men--in turn, scattered and drove them away, recovering most of his camp and artillery; but Hampton got off with Kilpatrick's private horses and a couple hundred prisoners, of which he boasted much in passing through Fayetteville. It was also reported that, in the morning after Hardee's army was all across the bridge at Cape Fear River, Hampton, with a small bodyguard, had remained in town, ready to retreat and burn the bridge as soon as our forces made their appearance. He was getting breakfast at the hotel when the alarm was given, when he and his escort took saddle, but soon realized that the alarm came from a set of our foragers, who, as usual, were extremely bold and rash. On these he turned, scattered them, killing some and making others prisoners; among them General Howard's favorite scout, Captain Duncan. Hampton then crossed the bridge and burned it. I took up my quarters at the old United States Arsenal, which was in fine order, and had been much enlarged by the Confederate authorities, who never dreamed that an invading army would reach it from the west; and I also found in Fayetteville the widow and
  • 75.
    daughter of myfirst captain (General Childs), of the Third Artillery, learned that her son Fred had been the ordnance-officer in charge of the arsenal, and had of course fled with Hardee's army. During the 11th. the whole army closed down upon Fayetteville, and immediate preparations were made to lay two pontoon bridges, one near the burned bridge, and another about four miles lower down. Sunday, March 12th, was a day of Sabbath stillness in Fayetteville. The people generally attended their churches, for they were a very pious people, descended in a large measure from the old Scotch Covenanters, and our men too were resting from the toils and labors of six weeks of as hard marching as ever fell to the lot of soldiers. Shortly after noon was heard in the distance the shrill whistle of a steamboat, which came nearer and nearer, and soon a shout, long and continuous, was raised down by the river, which spread farther and farther, and we all felt that it meant a messenger from home. The effect was electric, and no one can realize the feeling unless, like us, he has been for months cut off from all communication with friends, and compelled to listen to the croakings and prognostications of open enemies. But in a very few minutes came up through the town to the arsenal on the plateau behind a group of officers, among whom was a large, florid seafaring man, named Ainsworth, bearing a small mail-bag from General Terry, at Wilmington, having left at 2 p.m. the day before. Our couriers had got through safe from Laurel Hill, and this was the prompt reply. As in the case of our former march from Atlanta, intense anxiety had been felt for our safety, and General Terry had been prompt to open communication. After a few minutes' conference with Captain Ainsworth about the capacity of his boat, and the state of facts along the river, I instructed him to be ready to start back at 6 p.m., and ordered Captain Byers to get ready to carry dispatches to Washington. I also authorized General Howard to send back by this opportunity some of the fugitives who had traveled with his army all the way from Columbia, among whom were Mrs. Feaster and her two beautiful daughters.
  • 76.
    I immediately preparedletters for Secretary Stanton, Generals Halleck and Grant, and Generals Schofield, Foster, Easton, and Beckwith, all of which have been published, but I include here only those to the Secretary of War, and Generals Grant and Terry, as samples of the whole: HEADQUARTERS MILITARY DIVISION OF THE MISSISSIPPI, IN THE FIELD, FAYETTVILLE, NORTH CAROLINA, Sunday, March. 12, 1885. Hon. E. M. STANTON, Secretary of War. DEAR SIR: I know you will be pleased to hear that my army has reached this point, and has opened communication with Wilmington. A tug-boat came up this morning, and will start back at 6 P. M. I have written a letter to General Grant, the substance of which he will doubtless communicate, and it must suffice for me to tell you what I know will give you pleasure--that I have done all that I proposed, and the fruits seem to me ample for the time employed. Charleston, Georgetown, and Wilmington, are incidents, while the utter demolition of the railroad system of South Carolina, and the utter destruction of the enemy's arsenals of Columbia, Cheraw, and Fayetteville, are the principals of the movement. These points were regarded as inaccessible to us, and now no place in the Confederacy is safe against the army of the West. Let Lee hold on to Richmond, and we will destroy his country; and then of what use is Richmond. He must come out and fight us on open ground, and for that we must ever be ready. Let him
  • 77.
    stick behind hisparapets, and he will perish. I remember well what you asked me, and think I am on the right road, though a long one. My army is as united and cheerful as ever, and as full of confidence in itself and its leaders. It is utterly impossible for me to enumerate what we have done, but I inclose a slip just handed me, which is but partial. At Columbia and Cheraw we destroyed nearly all the gunpowder and cartridges which the Confederacy had in this part of the country. This arsenal is in fine order, and has been much enlarged. I cannot leave a detachment to hold it, therefore shall burn it, blow it up with gunpowder, and then with rams knock down its walls. I take it for granted the United States will never again trust North Carolina with an arsenal to appropriate at her pleasure. Hoping that good fortune may still attend my army. I remain your servant, W. T. SHERMAN, Major-General. HEADQUARTERS MILITARY DIVISION OF THE MISSISSIPPI, IN THE FIELD, FAYETTVILLE, NORTH CAROLINA, Sunday, March. 12, 1885. Lieutenant-General U. S. GRANT, commanding United States Army, City Point, Virginia. DEAR GENERAL: We reached this place yesterday at noon; Hardee, as usual, retreating across the Cape Fear, burning his bridges; but our pontoons will be up
  • 78.
    to-day, and, withas little delay as possible, I will be after him toward Goldsboro'. A tug has just come up from Wilmington, and before I get off from here, I hope to get from Wilmington some shoes and stockings, sugar, coffee, and flour. We are abundantly supplied with all else, having in a measure lived off the country. The army is in splendid health, condition, and spirits, though we have had foul weather, and roads that would have stopped travel to almost any other body of men I ever heard of. Our march, was substantially what I designed--straight on Columbia, feigning on Branchville and Augusta. We destroyed, in passing, the railroad from the Edisto nearly up to Aiken; again, from Orangeburg to the Congaree; again, from Colombia down to Kingsville on the Wateree, and up toward Charlotte as far as the Chester line; thence we turned east on Cheraw and Fayetteville. At Colombia we destroyed immense arsenals and railroad establishments, among which wore forty-three cannon. At Cheraw we found also machinery and material of war sent from Charleston, among which were twenty-five guns and thirty-six hundred barrels of powder; and here we find about twenty guns and a magnificent United States' arsenal. We cannot afford to leave detachments, and I shall therefore destroy this valuable arsenal, so the enemy shall not have its use; and the United States should never again confide such valuable property to a people who have betrayed a trust. I could leave here to-morrow, but want to clear my
  • 79.
    columns of thevast crowd of refugees and negroes that encumber us. Some I will send down the river in boats, and the rest to Wilmington by land, under small escort, as soon as we are across Cape Fear River. I hope you have not been uneasy about us, and that the fruits of this march will be appreciated. It had to be made not only to destroy the valuable depots by the way, but for its incidents in the necessary fall of Charleston, Georgetown, and Wilmington. If I can now add Goldsboro' without too much cost, I will be in a position to aid you materially in the spring campaign. Jos. Johnston may try to interpose between me here and Schofield about Newbern; but I think he will not try that, but concentrate his scattered armies at Raleigh, and I will go straight at him as soon as I get our men reclothed and our wagons reloaded. Keep everybody busy, and let Stoneman push toward Greensboro' or Charlotte from Knoxville; even a feint in that quarter will be most important. The railroad from Charlotte to Danville is all that is left to the enemy, and it will not do for me to go there, on account of the red-clay hills which are impassable to wheels in wet weather. I expect to make a junction with General Schofield in ten days. Yours truly, W. T. SHERMAN, Major-General.
  • 80.
    Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com