{"id":689,"date":"2014-05-09T11:54:16","date_gmt":"2014-05-09T06:24:16","guid":{"rendered":"http:\/\/www.prasadk.com\/my-press\/?p=689"},"modified":"2014-05-09T12:48:16","modified_gmt":"2014-05-09T07:18:16","slug":"backbone-js-tutorial","status":"publish","type":"post","link":"https:\/\/www.prasadk.com\/my-press\/backbone-js-tutorial\/","title":{"rendered":"backbone.js tutorial a walk through"},"content":{"rendered":"<h1>backbone.js tutorial<\/h1>\n<p><img loading=\"lazy\" alt=\"BACKBONE.JS\" src=\"http:\/\/i.stack.imgur.com\/kb2UF.png\" width=\"899\" height=\"160\" \/><\/p>\n<h1>Why do you need Backbone.js?<\/h1>\n<p>Building single-page web apps or complicated user interfaces will get extremely difficult by simply using\u00a0<a href=\"http:\/\/jquery.com\/\">jQuery<\/a>\u00a0or\u00a0<a href=\"http:\/\/mootools.net\/\">MooTools<\/a>. The problem is standard JavaScript libraries are great at what they do &#8211; and without realizing it you can build an entire application without any formal structure. You will with ease turn your application into a nested pile of jQuery callbacks, all tied to concrete DOM elements.<\/p>\n<p>I shouldn&#8217;t need to explain why building something without any structure is a bad idea. Of course you can always invent your own way of structuring your application but you miss out on the benefits of the open source community.<\/p>\n<h2>Why single page applications are the future<\/h2>\n<p>Backbone.js enforces that communication to the server should be done entirely through a RESTful API. The web is currently trending such that all data\/content will be exposed through an API. This is because the browser is no longer the only client, we now have mobile devices, tablet devices, Google Goggles and electronic fridges etc.<\/p>\n<h2>So how does Backbone.js help?<\/h2>\n<p>Backbone is an incredibly small library for the amount of functionality and structure it gives you. It is essentially MVC for the client and allows you to make your code modular. If you read through some of the beginner tutorials the benefits will soon become self evident and due to Backbone.js light nature you can incrementally include it in any current or future projects.<\/p>\n<h1>What is a model?<\/h1>\n<p>Across the internet the definition of\u00a0<a href=\"http:\/\/en.wikipedia.org\/wiki\/Model%E2%80%93view%E2%80%93controller\">MVC<\/a>\u00a0is so diluted that it&#8217;s hard to tell what exactly your model should be doing. The authors of backbone.js have quite a clear definition of what they believe the model represents in backbone.js.<\/p>\n<blockquote><p>Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.<\/p><\/blockquote>\n<p>So for the purpose of the tutorial let&#8217;s create a model.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n        }\r\n    });\r\n\r\n    var person = new Person;\r\n<\/code><\/pre>\n<\/div>\n<p>So\u00a0<em>initialize()<\/em>\u00a0is triggered whenever you create a new instance of a model( models, collections and views work the same way ). You don&#8217;t have to include it in your model declaration but you will find yourself using it more often than not.<\/p>\n<h2>Setting attributes<\/h2>\n<p>Now we want to pass some parameters when we create an instance of our model.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n        }\r\n    });\r\n\r\n    var person = new Person({ name: \"Thomas\", age: 67});\r\n    \/\/ or we can set afterwards, these operations are equivelent\r\n    var person = new Person();\r\n    person.set({ name: \"Thomas\", age: 67});\r\n\r\n<\/code><\/pre>\n<\/div>\n<p>So passing a JavaScript object to our constructor is the same as calling\u00a0<em>model.set()<\/em>. Now that these models have attributes set we need to be able to retrieve them.<\/p>\n<h2>Getting attributes<\/h2>\n<p>Using the\u00a0<em>model.get()<\/em>\u00a0method we can access model properties at anytime.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n        }\r\n    });\r\n\r\n    var person = new Person({ name: \"Thomas\", age: 67, child: 'Ryan'});\r\n\r\n    var age = person.get(\"age\"); \/\/ 67\r\n    var name = person.get(\"name\"); \/\/ \"Thomas\"\r\n    var child = person.get(\"child\"); \/\/ 'Ryan'\r\n\r\n<\/code><\/pre>\n<\/div>\n<h2>Setting model defaults<\/h2>\n<p>Sometimes you will want your model to contain default values. This can easily be accomplished by setting a property name &#8216;defaults&#8217; in your model declaration.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        defaults: {\r\n            name: 'Fetus',\r\n            age: 0,\r\n            child: ''\r\n        },\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n        }\r\n    });\r\n\r\n    var person = new Person({ name: \"Thomas\", age: 67, child: 'Ryan'});\r\n\r\n    var age = person.get(\"age\"); \/\/ 67\r\n    var name = person.get(\"name\"); \/\/ \"Thomas\"\r\n    var child = person.get(\"child\"); \/\/ 'Ryan'\r\n\r\n<\/code><\/pre>\n<\/div>\n<h2>Manipulating model attributes<\/h2>\n<p>Models can contain as many custom methods as you like to manipulate attributes. By default all methods are public.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        defaults: {\r\n            name: 'Fetus',\r\n            age: 0,\r\n            child: ''\r\n        },\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n        },\r\n        adopt: function( newChildsName ){\r\n            this.set({ child: newChildsName });\r\n        }\r\n    });\r\n\r\n    var person = new Person({ name: \"Thomas\", age: 67, child: 'Ryan'});\r\n    person.adopt('John Resig');\r\n    var child = person.get(\"child\"); \/\/ 'John Resig'\r\n\r\n<\/code><\/pre>\n<\/div>\n<p>So we can implement methods to get\/set and perform other calculations using attributes from our model at any time.<\/p>\n<h2>Listening for changes to the model<\/h2>\n<p>Now onto one of the more useful parts of using a library such as backbone. All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function we are going to bind a function call everytime we change the value of our attribute. In this case if the name of our &#8220;person&#8221; changes we will alert their new name.<\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        defaults: {\r\n            name: 'Fetus',\r\n            age: 0\r\n        },\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n            this.on(\"change:name\", function(model){\r\n                var name = model.get(\"name\"); \/\/ 'Stewie Griffin'\r\n                alert(\"Changed my name to \" + name );\r\n            });\r\n        }\r\n    });\r\n\r\n    var person = new Person({ name: \"Thomas\", age: 67});\r\n    person.set({name: 'Stewie Griffin'}); \/\/ This triggers a change and will alert()\r\n<\/code><\/pre>\n<\/div>\n<p>So we can bind the change listener to individual attributes or if we like simply &#8216;<em>this.on(&#8220;change&#8221;, function(model){});<\/em>&#8216; to listen for changes to all attributes of the model.<\/p>\n<h2>Interacting with the server<\/h2>\n<p>Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations.<\/p>\n<p>The\u00a0<code>id<\/code>\u00a0attribute of a model identifies how to find it on the database usually mapping to the\u00a0<a href=\"http:\/\/en.wikipedia.org\/wiki\/Surrogate_key\">surrogate key<\/a>.<\/p>\n<p>For the purpose of this tutorial imagine that we have a mysql table called\u00a0<code>Users<\/code>\u00a0with the columns\u00a0<code>id<\/code>,\u00a0<code>name<\/code>,\u00a0<code>email<\/code>.<\/p>\n<p>The server has implemented a RESTful URL\u00a0<code>\/user<\/code>\u00a0which allows us to interact with it.<\/p>\n<p>Our model definition shall thus look like;<\/p>\n<div>\n<pre><code>    var UserModel = Backbone.Model.extend({\r\n        urlRoot: '\/user',\r\n        defaults: {\r\n            name: '',\r\n            email: ''\r\n        }\r\n\r\n    });\r\n<\/code><\/pre>\n<\/div>\n<h3>Creating a new model<\/h3>\n<p>If we wish to create a new user on the server then we will instantiate a new UserModel and call\u00a0<code>save<\/code>. If the\u00a0<code>id<\/code>\u00a0attribute of the model is\u00a0<code>null<\/code>, Backbone.js will send a POST request to the urlRoot of the server.<\/p>\n<div>\n<pre><code>    var UserModel = Backbone.Model.extend({\r\n        urlRoot: '\/user',\r\n        defaults: {\r\n            name: '',\r\n            email: ''\r\n        }\r\n    });\r\n    var user = new Usermodel();\r\n    \/\/ Notice that we haven't set an `id`\r\n    var userDetails = {\r\n        name: 'Thomas',\r\n        email: 'thomasalwyndavis@gmail.com'\r\n    };\r\n    \/\/ Because we have not set a `id` the server will call\r\n    \/\/ POST \/user with a payload of {name:'Thomas', email: 'thomasalwyndavis@gmail.com'}\r\n    \/\/ The server should save the data and return a response containing the new `id`\r\n    user.save(userDetails, {\r\n        success: function (user) {\r\n            alert(user.toJSON());\r\n        }\r\n    })\r\n<\/code><\/pre>\n<\/div>\n<p>Our table should now have the values<\/p>\n<p>1, &#8216;Thomas&#8217;, &#8216;thomasalwyndavis@gmail.com&#8217;<\/p>\n<h3>Getting a model<\/h3>\n<p>Now that we have saved a new user model, we can retrieve it from the server. We know that the\u00a0<code>id<\/code>\u00a0is 1 from the above example.<\/p>\n<p>If we instantiate a model with an\u00a0<code>id<\/code>, Backbone.js will automatically perform a get request to the urlRoot + &#8216;\/id&#8217; (conforming to RESTful conventions)<\/p>\n<div>\n<pre><code>    \/\/ Here we have set the `id` of the model\r\n    var user = new Usermodel({id: 1});\r\n\r\n    \/\/ The fetch below will perform GET \/user\/1\r\n    \/\/ The server should return the id, name and email from the database\r\n    user.fetch({\r\n        success: function (user) {\r\n            alert(user.toJSON());\r\n        }\r\n    })\r\n<\/code><\/pre>\n<\/div>\n<h3>Updating a model<\/h3>\n<p>Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the\u00a0<code>save<\/code>\u00a0api call which is intelligent and will send a PUT request instead of a POST request if an\u00a0<code>id<\/code>\u00a0is present(conforming to RESTful conventions)<\/p>\n<div>\n<pre><code>    \/\/ Here we have set the `id` of the model\r\n    var user = new Usermodel({\r\n        id: 1,\r\n        name: 'Thomas',\r\n        email: 'thomasalwyndavis@gmail.com'\r\n    });\r\n\r\n    \/\/ Let's change the name and update the server\r\n    \/\/ Because there is `id` present, Backbone.js will fire\r\n    \/\/ PUT \/user\/1 with a payload of `{name: 'Davis', email: 'thomasalwyndavis@gmail.com'}`\r\n    user.save({name: 'Davis'}, {\r\n        success: function (model) {\r\n            alert(user.toJSON());\r\n        }\r\n    });\r\n<\/code><\/pre>\n<\/div>\n<h3>Deleting a model<\/h3>\n<p>When a model has an\u00a0<code>id<\/code>\u00a0we know that it exist on the server, so if we wish to remove it from the server we can call\u00a0<code>destroy<\/code>.\u00a0<code>destroy<\/code>\u00a0will fire off a DELETE \/user\/id (conforming to RESTful conventions).<\/p>\n<div>\n<pre><code>    \/\/ Here we have set the `id` of the model\r\n    var user = new Usermodel({\r\n        id: 1,\r\n        name: 'Thomas',\r\n        email: 'thomasalwyndavis@gmail.com'\r\n    });\r\n\r\n    \/\/ Because there is `id` present, Backbone.js will fire\r\n    \/\/ DELETE \/user\/1 \r\n    user.destroy({\r\n        success: function () {\r\n            alert('Destroyed');\r\n        }\r\n    });\r\n<\/code><\/pre>\n<\/div>\n<h3>Tips and Tricks<\/h3>\n<p><em>Get all the current attributes<\/em><\/p>\n<div>\n<pre><code>      \r\n    var person = new Person({ name: \"Thomas\", age: 67});\r\n    var attributes = person.toJSON(); \/\/ { name: \"Thomas\", age: 67}\r\n    \/* This simply returns a copy of the current attributes. *\/\r\n\r\n    var attributes = person.attributes;\r\n    \/* The line above gives a direct reference to the attributes and you should be careful when playing with it.   Best practise would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners. *\/\r\n<\/code><\/pre>\n<\/div>\n<p><em>Validate data before you set or save it<\/em><\/p>\n<div>\n<pre><code>    Person = Backbone.Model.extend({\r\n        \/\/ If you return a string from the validate function,\r\n        \/\/ Backbone will throw an error\r\n        validate: function( attributes ){\r\n            if( attributes.age &lt; 0 &amp;&amp; attributes.name != \"Dr Manhatten\" ){\r\n                return \"You can't be negative years old\";\r\n            }\r\n        },\r\n        initialize: function(){\r\n            alert(\"Welcome to this world\");\r\n            this.bind(\"error\", function(model, error){\r\n                \/\/ We have received an error, log it, alert it or forget it :)\r\n                alert( error );\r\n            });\r\n        }\r\n    });\r\n\r\n    var person = new Person;\r\n    person.set({ name: \"Mary Poppins\", age: -1 }); \r\n    \/\/ Will trigger an alert outputting the error\r\n\r\n    var person = new Person;\r\n    person.set({ name: \"Dr Manhatten\", age: -1 });\r\n    \/\/ God have mercy on our souls\r\n\r\n<\/code><\/pre>\n<\/div>\n<h1>What is a view?<\/h1>\n<p>Backbone views are used to reflect what your applications&#8217; data models look like. They are also used to listen to events and react accordingly. This tutorial will not be addressing how to bind models and collections to views but will focus on view functionality and how to use views with a JavaScript templating library, specifically\u00a0<a href=\"http:\/\/documentcloud.github.com\/underscore\/#template\">Underscore.js&#8217;s _.template<\/a>.<\/p>\n<p>We will be using\u00a0<a href=\"http:\/\/jquery.com\/\">jQuery 1.8.2<\/a>\u00a0as our DOM manipulator. It&#8217;s possible to use other libraries such as\u00a0<a href=\"http:\/\/mootools.net\/\">MooTools<\/a>\u00a0or\u00a0<a href=\"http:\/\/sizzlejs.com\/\">Sizzle<\/a>, but official Backbone.js documentation endorses jQuery. Backbone.View events may not work with other libraries other than jQuery.<\/p>\n<p>For the purposes of this demonstration, we will be implementing a search box.\u00a0<a href=\"http:\/\/jsfiddle.net\/tBS4X\/1\/\">A live example<\/a>\u00a0can be found on jsFiddle.<\/p>\n<div>\n<pre><code>    SearchView = Backbone.View.extend({\r\n        initialize: function(){\r\n            alert(\"Alerts suck.\");\r\n        }\r\n    });\r\n\r\n    \/\/ The initialize function is always called when instantiating a Backbone View.\r\n    \/\/ Consider it the constructor of the class.\r\n    var search_view = new SearchView();\r\n<\/code><\/pre>\n<\/div>\n<h2>The &#8220;el&#8221; property<\/h2>\n<p>The &#8220;el&#8221; property references the DOM object created in the browser. Every Backbone.js view has an &#8220;el&#8221; property, and if it not defined, Backbone.js will construct its own, which is an empty div element.<\/p>\n<p>Let us set our view&#8217;s &#8220;el&#8221; property to div#search_container, effectively making Backbone.View the owner of the DOM element.<\/p>\n<div>\n<pre><code>&lt;div id=\"search_container\"&gt;&lt;\/div&gt;\r\n\r\n&lt;script type=\"text\/javascript\"&gt;\r\n    SearchView = Backbone.View.extend({\r\n        initialize: function(){\r\n            alert(\"Alerts suck.\");\r\n        }\r\n    });\r\n\r\n    var search_view = new SearchView({ el: $(\"#search_container\") });\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<p><em>Note: Keep in mind that this binds the container element. Any events we trigger must be in this element.<\/em><\/p>\n<h2>Loading a template<\/h2>\n<p>Backbone.js is dependent on Underscore.js, which includes its own micro-templating solution. Refer to\u00a0<a href=\"http:\/\/documentcloud.github.com\/underscore\/\">Underscore.js&#8217;s documentation<\/a>\u00a0for more information.<\/p>\n<p>Let us implement a &#8220;render()&#8221; function and call it when the view is initialized. The &#8220;render()&#8221; function will load our template into the view&#8217;s &#8220;el&#8221; property using jQuery.<\/p>\n<div>\n<pre><code>&lt;script type=\"text\/template\" id=\"search_template\"&gt;\r\n  &lt;label&gt;Search&lt;\/label&gt;\r\n  &lt;input type=\"text\" id=\"search_input\" \/&gt;\r\n  &lt;input type=\"button\" id=\"search_button\" value=\"Search\" \/&gt;\r\n&lt;\/script&gt;\r\n\r\n&lt;div id=\"search_container\"&gt;&lt;\/div&gt;\r\n\r\n&lt;script type=\"text\/javascript\"&gt;\r\n    SearchView = Backbone.View.extend({\r\n        initialize: function(){\r\n            this.render();\r\n        },\r\n        render: function(){\r\n            \/\/ Compile the template using underscore\r\n            var template = _.template( $(\"#search_template\").html(), {} );\r\n            \/\/ Load the compiled HTML into the Backbone \"el\"\r\n            this.$el.html( template );\r\n        }\r\n    });\r\n\r\n    var search_view = new SearchView({ el: $(\"#search_container\") });\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<p><em>Tip: Place all your templates in a file and serve them from a CDN. This ensures your users will always have your application cached.<\/em><\/p>\n<h2>Listening for events<\/h2>\n<p>To attach a listener to our view, we use the &#8220;events&#8221; attribute of Backbone.View. Remember that event listeners can only be attached to child elements of the &#8220;el&#8221; property. Let us attach a &#8220;click&#8221; listener to our button.<\/p>\n<div>\n<pre><code>&lt;script type=\"text\/template\" id=\"search_template\"&gt;\r\n  &lt;label&gt;Search&lt;\/label&gt;\r\n  &lt;input type=\"text\" id=\"search_input\" \/&gt;\r\n  &lt;input type=\"button\" id=\"search_button\" value=\"Search\" \/&gt;\r\n&lt;\/script&gt;\r\n\r\n&lt;div id=\"search_container\"&gt;&lt;\/div&gt;\r\n\r\n&lt;script type=\"text\/javascript\"&gt;\r\n    SearchView = Backbone.View.extend({\r\n        initialize: function(){\r\n            this.render();\r\n        },\r\n        render: function(){\r\n            var template = _.template( $(\"#search_template\").html(), {} );\r\n            this.$el.html( template );\r\n        },\r\n        events: {\r\n            \"click input[type=button]\": \"doSearch\"\r\n        },\r\n        doSearch: function( event ){\r\n            \/\/ Button clicked, you can access the element that was clicked with event.currentTarget\r\n            alert( \"Search for \" + $(\"#search_input\").val() );\r\n        }\r\n    });\r\n\r\n    var search_view = new SearchView({ el: $(\"#search_container\") });\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<h2>Tips and Tricks<\/h2>\n<p><em>Using template variables<\/em><\/p>\n<div>\n<pre><code>&lt;script type=\"text\/template\" id=\"search_template\"&gt;\r\n    &lt;!-- Access template variables with &lt;%= %&gt; --&gt;\r\n    &lt;label&gt;&lt;%= search_label %&gt;&lt;\/label&gt;\r\n    &lt;input type=\"text\" id=\"search_input\" \/&gt;\r\n    &lt;input type=\"button\" id=\"search_button\" value=\"Search\" \/&gt;\r\n&lt;\/script&gt;\r\n\r\n&lt;div id=\"search_container\"&gt;&lt;\/div&gt;\r\n\r\n&lt;script type=\"text\/javascript\"&gt;\r\n     SearchView = Backbone.View.extend({\r\n        initialize: function(){\r\n            this.render();\r\n        },\r\n        render: function(){\r\n            \/\/Pass variables in using Underscore.js Template\r\n            var variables = { search_label: \"My Search\" };\r\n            \/\/ Compile the template using underscore\r\n            var template = _.template( $(\"#search_template\").html(), variables );\r\n            \/\/ Load the compiled HTML into the Backbone \"el\"\r\n            this.$el.html( template );\r\n        },\r\n        events: {\r\n            \"click input[type=button]\": \"doSearch\"  \r\n        },\r\n        doSearch: function( event ){\r\n            \/\/ Button clicked, you can access the element that was clicked with event.currentTarget\r\n            alert( \"Search for \" + $(\"#search_input\").val() );\r\n        }\r\n    });\r\n\r\n    var search_view = new SearchView({ el: $(\"#search_container\") });\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<h1>What is a router?<\/h1>\n<p>Backbone routers are used for routing your applications URL&#8217;s when using hash tags(#). In the traditional MVC sense they don&#8217;t necessarily fit the semantics and if you have read &#8220;<a href=\"http:\/\/backbonetutorials.com\/what-is-a-view\">What is a view?<\/a>&#8221; it will elaborate on this point. Though a Backbone &#8220;router&#8221; is still very useful for any application\/feature that needs URL routing\/history capabilities.<\/p>\n<p>Defined routers should always contain at least one route and a function to map the particular route to. In the example below we are going to define a route that is always called.<\/p>\n<p>Also note that routes interpret anything after &#8220;#&#8221; tag in the URL. All links in your application should target &#8220;#\/action&#8221; or &#8220;#action&#8221;. (Appending a forward slash after the hashtag looks a bit nicer e.g. http:\/\/example.com\/#\/user\/help)<\/p>\n<div>\n<pre><code>&lt;script&gt;\r\n    var AppRouter = Backbone.Router.extend({\r\n        routes: {\r\n            \"*actions\": \"defaultRoute\" \/\/ matches http:\/\/example.com\/#anything-here\r\n        }\r\n    });\r\n    \/\/ Initiate the router\r\n    var app_router = new AppRouter;\r\n\r\n    app_router.on('route:defaultRoute', function(actions) {\r\n        alert(actions);\r\n    })\r\n\r\n    \/\/ Start Backbone history a necessary step for bookmarkable URL's\r\n    Backbone.history.start();\r\n\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<p><span style=\"font-size: 1.5em; line-height: 1.5em;\">Dynamic Routing<\/span><\/p>\n<p>Most conventional frameworks allow you to define routes that contain a mix of static and dynamic route parameters. For example you might want to retrieve a post with a variable id with a friendly URL string. Such that your URL would look like &#8220;http:\/\/example.com\/#\/posts\/12&#8221;. Once this route was activated you would want to access the id given in the URL string. This example is implemented below.<\/p>\n<div>\n<pre><code>&lt;script&gt;\r\n    var AppRouter = Backbone.Router.extend({\r\n        routes: {\r\n            \"posts\/:id\": \"getPost\",\r\n            \"*actions\": \"defaultRoute\" \/\/ Backbone will try match the route above first\r\n        }\r\n    });\r\n    \/\/ Instantiate the router\r\n    var app_router = new AppRouter;\r\n    app_router.on('route:getPost', function (id) {\r\n        \/\/ Note the variable in the route definition being passed in here\r\n        alert( \"Get post number \" + id );   \r\n    });\r\n    app_router.on('route:defaultRoute', function (actions) {\r\n        alert( actions ); \r\n    });\r\n    \/\/ Start Backbone history a necessary step for bookmarkable URL's\r\n    Backbone.history.start();\r\n\r\n&lt;\/script&gt;\r\n<\/code><\/pre>\n<\/div>\n<p><span style=\"font-size: 1.5em; line-height: 1.5em;\">Dynamic Routing Cont. &#8220;:params&#8221; and &#8220;*splats&#8221;<\/span><\/p>\n<p>Backbone uses two styles of variables when implementing routes. First there are &#8220;:params&#8221; which match any URL components between slashes. Then there are &#8220;<em>splats&#8221; which match any number of URL components. Note that due to the nature of a &#8220;<\/em>splat&#8221; it will always be the last variable in your URL as it will match any and all components.<\/p>\n<p>Any &#8220;*splats&#8221; or &#8220;:params&#8221; in route definitions are passed as arguments (in respective order) to the associated function. A route defined as &#8220;\/:route\/:action&#8221; will pass 2 variables (\u201croute\u201d and \u201caction\u201d) to the callback function. (If this is confusing please post a comment and I will try articulate it better)<\/p>\n<p>Here are some examples of using &#8220;:params&#8221; and &#8220;*splats&#8221;<\/p>\n<div>\n<pre><code>        routes: {\r\n\r\n            \"posts\/:id\": \"getPost\",\r\n            \/\/ &lt;a href=\"http:\/\/example.com\/#\/posts\/121\"&gt;Example&lt;\/a&gt;\r\n\r\n            \"download\/*path\": \"downloadFile\",\r\n            \/\/ &lt;a href=\"http:\/\/example.com\/#\/download\/user\/images\/hey.gif\"&gt;Download&lt;\/a&gt;\r\n\r\n            \":route\/:action\": \"loadView\",\r\n            \/\/ &lt;a href=\"http:\/\/example.com\/#\/dashboard\/graph\"&gt;Load Route\/Action View&lt;\/a&gt;\r\n\r\n        },\r\n\r\n        app_router.on('route:getPost', function( id ){ \r\n            alert(id); \/\/ 121 \r\n        });\r\n        app_router.on('route:downloadFile', function( path ){ \r\n            alert(path); \/\/ user\/images\/hey.gif \r\n        });\r\n        app_router.on('route:loadView', function( route, action ){ \r\n            alert(route + \"_\" + action); \/\/ dashboard_graph \r\n        });\r\n<\/code><\/pre>\n<\/div>\n<p>Routes are quite powerful and in an ideal world your application should never contain too many. If you need to implement hash tags with SEO in mind, do a google search for &#8220;google seo hashbangs&#8221;. Also check out\u00a0<a href=\"http:\/\/seo.apiengine.io\/\">Seo Server<\/a><\/p>\n<div>\n<div id=\"post\">\n<h1>What is a collection?<\/h1>\n<p>Backbone collections are simply an ordered set of\u00a0<a href=\"http:\/\/backbonetutorials.com\/what-is-a-model\">models<\/a>. Such that it can be used in situations such as;<\/p>\n<ul>\n<li>Model: Student, Collection: ClassStudents<\/li>\n<li>Model: Todo Item, Collection: Todo List<\/li>\n<li>Model: Animal, Collection: Zoo<\/li>\n<\/ul>\n<p>Typically your collection will only use one type of model but models themselves are not limited to a type of collection;<\/p>\n<ul>\n<li>Model: Student, Collection: Gym Class<\/li>\n<li>Model: Student, Collection: Art Class<\/li>\n<li>Model: Student, Collection: English Class<\/li>\n<\/ul>\n<p>Here is a generic Model\/Collection example.<\/p>\n<div>\n<pre><code>  var Song = Backbone.Model.extend({\r\n      initialize: function(){\r\n          console.log(\"Music is the answer\");\r\n      }\r\n  });\r\n\r\n  var Album = Backbone.Collection.extend({\r\n    model: Song\r\n  });\r\n<\/code><\/pre>\n<\/div>\n<h2>Building a collection<\/h2>\n<p>Now we are going to populate a collection with some useful data.<\/p>\n<div>\n<pre><code>    var Song = Backbone.Model.extend({\r\n        defaults: {\r\n            name: \"Not specified\",\r\n            artist: \"Not specified\"\r\n        },\r\n        initialize: function(){\r\n            console.log(\"Music is the answer\");\r\n        }\r\n    });\r\n\r\n    var Album = Backbone.Collection.extend({\r\n        model: Song\r\n    });\r\n\r\n    var song1 = new Song({ name: \"How Bizarre\", artist: \"OMC\" });\r\n    var song2 = new Song({ name: \"Sexual Healing\", artist: \"Marvin Gaye\" });\r\n    var song3 = new Song({ name: \"Talk It Over In Bed\", artist: \"OMC\" });\r\n\r\n    var myAlbum = new Album([ song1, song2, song3]);\r\n    console.log( myAlbum.models ); \/\/ [song1, song2, song3]<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>backbone.js tutorial Why do you need Backbone.js? Building single-page web apps or complicated user interfaces will get extremely difficult by simply using\u00a0jQuery\u00a0or\u00a0MooTools. The problem is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0},"categories":[7,6],"tags":[],"_links":{"self":[{"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/posts\/689"}],"collection":[{"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/comments?post=689"}],"version-history":[{"count":4,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/posts\/689\/revisions"}],"predecessor-version":[{"id":693,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/posts\/689\/revisions\/693"}],"wp:attachment":[{"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/media?parent=689"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/categories?post=689"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.prasadk.com\/my-press\/wp-json\/wp\/v2\/tags?post=689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}