Loading presentation...

Present Remotely

Send the link below via email or IM


Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.


Introduction to Backbone JS

Workshop run for Substance on 10th April 2013 to take staff through how to use Backbone JS to implement an MV* approach to Javascript coding

Neil Young

on 10 April 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Introduction to Backbone JS

Other services are handled through the use of utilty files True Blood – The Revelation Structure Creating a cleaner code structure The Router: Example – A Simple Tweet Aggregator
//build the model for the tweet
var Tweet = Backbone.Model.extend({}); Example – A Simple Tweet Aggregator Create, Retrieve, Update and Destroy (CRUD) is the core functionality to any API. Backbone & The Server //create an application router
var AppRouter = Backbone.Router.extend({
routes : {
“*actions” : “defaultAction”, //used as a default
“games-page” : “gamesPage”
//create the app router
var appRouter = new AppRouter( );
//listen to the routers event
appRouter.on(‘route:gamesPage’, function(){
//creation of your models and views here
//start the backbone history (necessary step for bookmarkable urls)
Backbone.history.start(); Backbone Router (or Controller) //create a view
var GamesView = Backbone.View.extend({
//assign the element that will hold the view
el: $("#page"),
//function to render the view
render: function(){
//renders the template
this.$el.html(_.template( “<div id=“”><%=value%></div>”, { value: “my value” } ));
//initialise the view
var gamesView = new GamesView( );
//render the view
gamesView.render(); Backbone Views

//create a collection object that stores a Game model
var GamesCollection = Backbone.Collection.extend({
model: GameModel
//create a GameModel object
var GameModel = Backbone.Model.extend();
//add GameModels to the collection
new GamesCollection.add([
new GameModel( { id: 1, title: “Super Mario Kart”, platform: “Nintendo Wii” } ),
new GameModel( { id: 2, title: “Call of Duty: Black Ops II”, platform: “Xbox 360” } )

]); The Backbone model Backbone.js is a Javascript framework used to give structure to an SPA (Single Page Application). What is Backbone.js Backbone’s Website – http://www.backbonejs.org
Underscore Website – http://www.underscorejs.org/
A great Backbone AMD tutorial - http://backbonetutorials.com/organizing-backbone-using-modules/
Code School (we have an account) Further Reading Other considerations //Example of a module definition
//Ensures jquery is loaded before underscore which is then followed by Backbone
//Backbone has a hard dependancy on underscore in order to run
define([ ‘jquery’, ‘underscore’, ‘backbone’ ], function( $, _, Backbone ){
//your model, router, view object in here
}) AMD (Asynchronous Module Definitions) RequireJS is used to load a series of javascript files asynchronously What is RequireJS?
//create an instance of the tweets collection object
var tweetsCollection = new TweetsCollection( );

//creat the app router (controller)
var appRouter = new AppRouter();

//the following listens for a change to the address bar for any urls that do not match our tweets url!
appRouter.on('route:defaultAction', function( actions ){
console.log( "All other traffic directed here" );

//listen for the route call for showing tweets
appRouter.on('route:showTweets', function( actions ){
//fetch the tweets from the twitter api
tweetsCollection.fetch( { success: function(){
//create the tweets view
var tweetsView = new TweetsView( { model: tweetsCollection } );
//render teh tweets
} } );

// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start(); Example – A Simple Tweet Aggregator //create a collection object that stores a Game model
var GamesCollection = Backbone.Collection.extend({
model: GameModel
//create a GameModel object
var GameModel = Backbone.Model.extend();
//add GameModel’s to the collection
var gamesCollection = new GamesCollection.add([
new GameModel ( { id: 1, title: “Super Mario Kart”, platform: “Nintendo Wii” } ),
new GameModel ( { id: 2, title: “Call of Duty: Black Ops II”, platform: “Xbox 360” } )
//create a view and add the collection to the view
var gamesView = new GamesView( { model: gamesCollection } );
//render the view
gamesView.render(); Displaying your model data in your view MVC is a way of abstracting your data inside a model from your page views via a controller. What is MVC? www.backbonejs.org Introduction to: There are two components used to control models in Backbone; collections & models Handles how data is viewed in the browser and any events that happen on the page. The router is used to link your views to your models. Backbone & SEO SEO = Search Engine Optimisation Backbone & The HTML5 History API push state Allows abstraction between server data, html (using templates) & javascript Can connect to any API (Application Programming Interface) Based on an MVC (or MV*) principal Supports custom event handling It provides four core parts, collections, models, router & view A collection is made up of a series of models Example of a view in its simplest form: The router ‘routes’ address urls to your backbone views Gracefully falls back on older browsers that do not support it (the usual culprits - IE!) Backbone manages your urls by using the HTML 5 history api (push/pop state) Measured on your content, urls, links to your website A way of improving the search ranking for your website Once we have our controller we can build our model and pass it to our view Backbone has functionality to connect to your server to perform these actions. An API is built on server side code (outside the scope of this workshop) An example is the Facebook Graph API - allows us to connect to it and gather and manipulate information //create a games collection object
var GamesCollection = Backbone.Collection.extend({
model: GameModel,
url: “api/games” // (url can also be a function so we can change it with passed parameters )
//fetch data from the server
gamesCollection.fetch( { parse:false, success: function( games){
var gamesView = new GamesView( { model: games } );
//render the view
gamesView .render( );
} } ); //build the collection to control the models
var TweetsCollection = Backbone.Collection.extend({
//specify the model
model: Tweet,
//url to fetch data from
url: "http://search.twitter.com/search.json?q=from:facebook+OR+@facebook&rpp=10",
//overide the syncronisation function as we need to use jsonp to avoid cross domain policy errors
sync: function(method, model, options){
options.timeout = 10000;
options.dataType = "jsonp";
return Backbone.sync(method, model, options);
//parse the response from the server
parse: function(response) {
//return the results of the search
return response.results;
}); The Model: The Collection: //app router (controller) to handle addressing
var AppRouter = Backbone.Router.extend({
//build the routes for the url addresses
routes : {
'tweets' : 'showTweets',
'*actions' : 'defaultAction'
}); //build the view to handle the tweets
var TweetsView = Backbone.View.extend({
// element to render the tweets to...
el: $("#tweets"),
//function to render the tweets
render: function( ){
//start building our html
var html = '';
//loop through our collection of tweets
_.each(this.model.toJSON(), function(tweet){
//build the html for that tweet
html += _.template( $("#tweet-template").html(), { tweet: tweet } );
//assign the html to the tweets div
}); The View: Setting up the application What if we want to have our different models, collections, router(s) and views stored in separate files in our framework. There are ways that we can improve the structure of a Backbone application even further! Achieved using; RequireJS; a tool that utilises AMD (Asynchronous Module Definition) Ensures only one script declaration will exist in the index page making code cleaner and easier to manage Why do we do this ? Simple, say we want to load Jquery and then ensure that a plugin is loaded after Jquery… Its purpose is to queue up the scripts until they are needed. Documentation: http://www.requirejs.org Modules are defined and then declared. Advantage is that we can tell the application what the module needs before it loads (its dependencies) Works with RequireJS to load all your script library files (Jquery, Backbone, Underscore etc..) from modules AMD is used as a way to abstract all your models, collections, views and routers into a module based structure. Each model, view and router are built into separate modules. These module components determine what needs to be loaded before the module can run Custom events are handled through an Event Mediator object How do we handle the following problems? Memory leaks (referred to as Zombies) Issue are that objects are created in a single page application but left there when a user navigates to another page – causes memory “zombies” We use a ViewManager to store our views and then dispose of them when we load a new page File size RequireJS provides us with a great little command line tool called r.js Allows us to create a build profile and then it compiles down the file to one javascript file (including templates!!) True Blood application went from around 5MB to 260KB! The problem with urls in the past are that they used 'hashbangs'. For example /#!/your-url was used to navigate to a page in a SPA Backbone allows us to use the history api and fallback to the 'hashbang' for older browsers //when you call the start method of the history api you
//pass the root to specify what to start the url rewriting at.
Backbone.history.start( { pushState: true, root: "/" } ); //example - True Blood The Revelation
Backbone.history.start( { pushState: true, root: "/true-blood/mosaic/" } ); Javascript allows changes to be made to a web document on the fly. Javascript & JQuery JQuery is a framework and was developed by John Resig to simplify the authoring of Javascript Example, selecting an element inside a document: Javascript:
var myElement = document.getElementById("myElement").value; JQuery:
var myElement = $("myElement").val(); Thank You! A set of examples can be found in my drop folder called "Backbone JS Course Source Files.zip" that:
- Demonstrates how to build a procedural (for smaller applications) Backbone application using the Twitter & Facebook API's.
- Demonstrates a modular application using the same approach
- Demonstrates how to use the ViewManager and how it removes "view zombies"
- Demonstrates how the EventMediator works with an XML Utility
Full transcript