window
objectl.This is an old revision of the document!
Table of Contents
~~SLIDESHOW~~
Introduction to Backbone.js
Contact Hour 17: To be discussed on Wednesday 5th March, 2013.
Lecturer: Dr Chris P. Jobling.
An introduction to Backbone based on the Free Udemy course Learn Backbone.js and StackMob by Sidney Maestre with a contribution from Christophe Coenraets.
You can watch the video below in which Sid goes through much the same example at a 2013 San Francisco HTML5 Developer's Meetup. (published by Marakana.tv).
<html> <iframe width=“560” height=“315” src=“http://www.youtube.com/embed/jM8KE_Fa6JI” frameborder=“0” allowfullscreen></iframe> </html>
Introduction to Backbone.js
Please review the Pearltree used in the previous session for some background to MVC and Client-side JavaScript MVC Frameworks.
Contents of this Session
All of the Examples
For convenience, all examples, jsFiddles and source code are linked to backbonejs-hands-on/index.html (web/backbonejs-hands-on/index.html
) on the latest update to the eg-259-vm repository.
Some JavaScript Conventions
- Common pattern – self-calling anonymous function
(function(){ var foo = bar; })();
This pattern is used to prevent any code/variables/functions declared inside the body leaking out into the global namespace.
Even so, if you omit the var
:
(function(){ foo = bar; })();
The variable foo would become a global variable1)
Passing in the jQuery variable
(function($){ var foo = bar; })(jQuery);
This uses a “closure” to ensure that the jQuery
variable is available inside the scope of the anonymous self-calling function as $
. This will be true even if $
was redefined after loading this function.
The JavaScript Module Pattern
var app = (function($){ var foo = "bar"; return { name : 'module pattern', setFoo: function(name) { foo = name; }, getFoo: function() { return foo; } }; })(jQuery);
See jsFiddle and 00-module/index.html
Ensures that methods and properties are name-spaced (e.g. app.name
, app.setFoo
, app.getFoo
) to avoid collisions and also that only properties and methods that are made available outside the module. Any dependencies, e.g. in this case jQuery, are passed in as arguments to the self-calling anonymous function.
The Object Namespacing Pattern
var app = app || {}; app.model = app.model || {}; app.routers = app.routers || {}; app.collections = app.collections || {}; ... app.model.Project = Backbone.Model.extend({}); app.model.ProjectSelection = Backbone.Model.extend({}); app.routers.Application = Backbone.Router.extend({}); app.routers.Projects = Backbone.Collection.extend({}); app.collections.ProjectSelection = Backbone.Collection.extend({});
This is not used in this example project, but is recommended by Addy Osmani in his forthcoming O'Reilly book Developing Backbone.js Applications (Source code and copy, in various e-book formats, on GitHub at addyosmani/backbone-fundamentals). It is a pattern worth considering for your coursework as well.
MVC Defined
- Model – represents data in the application. May also include behaviour, for example for validation, initialisation, computer properties.
- View – representation of the data in the web page. Could be several different views: for example models in a list, a single model displayed, a model with controls for editing; an empty view for creating new data items, etc.
- Controller – traditionally, a mediator for marshalling user interactions and coordinating changes in the model(s) based on user actions and updating views. In most browser-based MVC frameworks, the controller takes on the role of recording the state and views changed based on change events issued by models,
In server-side MVC applications, the controller typically responds to URLs and coodinates the retrieval of model data from databases and pssing them on to HTML templates which are then passed on to the client.
In REST-based applications, the application is much more controller and model-based. Data is typically passed to the browser for rendering as a view. Often, these days, as JSON objects.
Adding Backbone
<!-- Script libraries --> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://static.stackmob.com/js/json2-min.js"></script> <script src="http://static.stackmob.com/js/underscore-1.3.3-min.js"></script> <script src="http://static.stackmob.com/js/backbone-0.9.2-min.js"></script>
Code Review
- Open index.html
- Open Web Inspector
Models and Collections
- Defining models
- Model defualts and methods
- Change events on models
- Collections
- Iteration on collections
- Change events on collections
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Model Defaults and Methods
Project = Backbone.Model.extend({ defaults: { title: "Project 1" }, updateTitle: function(newTitle) { this.set("title", newTitle); } }); firstProject = new Project(); console.log(firstProject.toJSON());
Listeners
firstProject.on('change:title', function () { console.log("you've updated the title"); console.log(this.get('title')); });
Collections
Project = Backbone.Model.extend(); Projects = Backbone.Collection.extend({ Model: Project, url: "#" });
URL is “RESTful endpoint” which backbone uses to retrive collections.
Collections of Models
projects = new Projects([{ title: "Project 1" }, { title: "Project 2" }]); console.log(projects.toJSON());
Iterating Through a Collection
projects.each(function (project) { console.log(project.get('title')); });
each
is a method provided by the underscore library. It loops through a collection, returning each element which is then passed on to a function.
Events on Collections
: projects.on('add remove', function (event) { console.log("you've changed the collection"); }); var firstProject = new Project({ name: 'Project 1' }); projects.add(firstProject);
In this example, a change event is triggered if an item is added to the collection, or if an item is removed from the collection. In Backbone, wiews can subscribe to such events and redraw the collection should any item change.
Views and Templates
- Views
- Templates
Define View
(function ($) { HomeView = Backbone.View.extend({}); })(jQuery);
A view (in HTML) is a rectangular area on the page that observes models and collections and updates themselves when the models change. In JavaScript MVC they can also be the target of user interactions and can generate events themselves.
Render View
(function ($) { HomeView = Backbone.View.extend({ render: function () { this.$el.append("<h1>My Projects App</h1>"); return this; } }); })(jQuery);
Render is a function that is used to build the DOM that represents the HTML in the view. Note $el
is the jQuery representation of the views element el
(which by default is a div).
Render View
(function ($) { HomeView = Backbone.View.extend({ render: function () { this.$el.append("<h1>My Projects App</h1>"); return this; } }); })(jQuery);
Render is a function that is used to build the DOM that represents the HTML in the view. Note $el
is the jQuery representation of the views element el
(which by default is a div).
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Define Model
(function ($) { Project = Backbone.Model.extend({}); firstProject = new Project({ title: 'Project 1' }); })(jQuery);
Application Router
Events
Complete CRUD App (in-memory storage)
Summary of this Session
We probably didn't get through all this, but please do take some time to explore!
Homework Exercises
- Come up with something
What's Next?
Part 3: Server-Side Programming
- Basic Web Server Operation
- Interactive Services, CGI and REST