Separation of concerns - Application Logic vs User Interface
Structure the code
Re-use
Decoupled Code
JavaScript MVC frameworks don’t always strictly follow the MVC pattern
Some solutions (including Backbone.js) merge the responsibility of the Controller into the View, while other approaches add additional components into the mix.
For this reason we refer to such frameworks as following the MV* pattern; that is, you’re likely to have a Model and a View, but a distinct Controller might not be present and other components may come into play.
Contain the logic behind the presentation of the model’s data to the user
Achieved using JavaScript templating (e.g., Underscore Microtemplates, Mustache, jQuery-tmpl, etc.)
A view’s render() method can be bound to a model’s change() event,
to instantly reflect model changes without refresh.
Provide a way for you to connect URLs
Pages that need to be bookmarkable, shareable or back-button-able
Backbone.history
monitor hashchange - Backbone.history.start()
Asynchronous Module Definitions (API)
Designed to load modular code asynchronously in the browser
Particularly well suited for the browser environment where
synchronous loading of modules incurs
Performance Issues
var helloWorld = function() {
return "Hello world!";
};
describe("Hello world", function() {
it("says hello", function() {
expect(helloWorld()).toEqual("Hello world!");
});
});
after(function () {
// When the test either fails or passes, restore the original
// jQuery ajax function (Sinon.JS also provides tools to help
// test frameworks automate clean-up like this)
jQuery.ajax.restore();
});
it("makes a GET request for todo items", function () {
sinon.stub(jQuery, "ajax");
getTodos(42, sinon.spy());
assert(jQuery.ajax.calledWithMatch({ url: "/todo/42/items" }));
});
describe("when instantiated with model literal", function() {
beforeEach(function() {
this.todoStub = sinon.stub(window, "Todo");
this.model = new Backbone.Model({
id: 5,
title: "Foo"
});
this.todoStub.returns(this.model);
this.todos = new Todos();
this.todos.model = Todo; // reset model relationship to use stub
this.todos.add({
id: 5,
title: "Foo"
});
});
afterEach(function() {
this.todoStub.restore();
});
it("should add a model", function() {
expect(this.todos.length).toEqual(1);
});
it("should find a model by id", function() {
expect(this.todos.get(5).get("id")).toEqual(5);
});
});