<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
<channel>
	<title>duckbox: Blog of Chris Grant</title>
	
	<link>http://duckbox.net/</link>
	<description />
	<language>en</language>
	<sy:updatePeriod>daily</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/duckboxblog" /><feedburner:info uri="duckboxblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Kick ass with Backbone</title>
		<link>http://feedproxy.google.com/~r/duckboxblog/~3/ygC8dNpMLPk/kick-ass-with-backbone</link>
		<pubDate>Sun, 13 May 2012 18:54:02 +0100</pubDate>
		<dc:creator>Chris Grant</dc:creator>
		<description>
						<![CDATA[ <p><a href="http://documentcloud.github.com/backbone/" target="_blank" class="external">Backbone.js</a> is becoming the most go to tool for web applications due to its lightweight flexibility. There has been a lot of debate around JavaScript MVC libraries and <a href="http://addyosmani.github.com/todomvc/labs/" target="_blank" class="external">which is better</a>. Personally I have have not explored many alternatives in depth myself, which I will soon rectify. But on the table, I am having too much fun with Backbone.</p>

<h3>Mah Controller!?</h3>

<p><span style="float:right;padding-left:20px"> <img height="150" alt="phat" src="http://duckbox.net/articles/resources/1/phat-controller.gif" /> </span></p>

<p>I humorously call Backbone a  MVCn, which is shorthand for <em>Model-View-Collection</em>. There is no traditional controller as other robust JS MVCs state they have. The Collection being, a <em>collection</em> of Backbone Models (super relational-pimped objects, naturally)</p>

<p>It is difficult to grasp the convention to begin with, but once you get your mind around it, it is relatively simple.</p>

<p>My intention is not to explain every ounce of Backbones universal definition and spirituality, many other <a href="https://github.com/addyosmani/backbone-fundamentals" target="_blank" class="external">good people</a> have done that</p>

<p> ]]>
		</description>
		<content:encoded><![CDATA[
			 <p><a href="http://documentcloud.github.com/backbone/" target="_blank" class="external">Backbone.js</a> is becoming the most go to tool for web applications due to its lightweight flexibility. There has been a lot of debate around JavaScript MVC libraries and <a href="http://addyosmani.github.com/todomvc/labs/" target="_blank" class="external">which is better</a>. Personally I have have not explored many alternatives in depth myself, which I will soon rectify. But on the table, I am having too much fun with Backbone.</p>

<h3>Mah Controller!?</h3>

<p><span style="float:right;padding-left:20px"> <img height="150" alt="phat" src="http://duckbox.net/articles/resources/1/phat-controller.gif" /> </span></p>

<p>I humorously call Backbone a  MVCn, which is shorthand for <em>Model-View-Collection</em>. There is no traditional controller as other robust JS MVCs state they have. The Collection being, a <em>collection</em> of Backbone Models (super relational-pimped objects, naturally)</p>

<p>It is difficult to grasp the convention to begin with, but once you get your mind around it, it is relatively simple.</p>

<p>My intention is not to explain every ounce of Backbones universal definition and spirituality, many other <a href="https://github.com/addyosmani/backbone-fundamentals" target="_blank" class="external">good people</a> have done that</p>

<p></p>

<h3>Setting up</h3>

<p>In order to have a go at coding with Backbone, we need to bring in some libs.</p>

<pre class="prettyprint">&lt;!-- In footer of markup --&gt;
&lt;script src="jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="underscore-min.js"&gt;&lt;/script&gt;
&lt;script src="backbone-min.js"&gt;&lt;/script&gt;

&lt;!-- Your file --&gt;
&lt;script src="app.js"&gt;&lt;/script&gt;
</pre>

<p>We all know what jQuery is, it is a requirement for these examples, but not a requirement for using Backbone. Feel free to use whatever lib of your preference. <a href="http://zeptojs.com" target="_blank" class="external">Zepto</a> naturally falls on top of jQuery, use this if required.</p>

<p>The <a href="http://documentcloud.github.com/underscore/" target="_blank" class="external">Underscore</a> library is by the creators of Backbone and is a Backbone dependancy, so please make sure it is present. Consider it being Batman's utility belt, only for JavaScript.</p>

<p>As our Backbone code will be wrapped in a self-executing function, your files will need to be at the bottom of your markup, or the app.js at least.</p>

<pre class="prettyprint">// Inside app.js

// Self executing wrapper
(function ($) {

    // Our code goes here

})(jQuery);
</pre>

<p>There are more robust ways for setting up our code, but for simplicity, we shall use this.</p>

<h3>Models</h3>

<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><footer><span> Backbone.js on Models </span></footer>
</blockquote>

<p>Models are the key ingredient to the cake, this is where we contain and manipulate all of our data.</p>

<pre class="prettyprint">var Item = Backbone.Model;
// We now have a new Model type defined in Item

var bacon = new Item({ title: 'Bacon' });
// We have created a new Item Model, with the title attribute of 'Bacon'
</pre>

<p>The Backbone model has the traditional setters and getters.</p>

<pre class="prettyprint">bacon.get('title');
// =&gt; Bacon

bacon.set({ price: 2.99 });
// Damn expensive Bacon

bacon.get('price');
// =&gt; 2.99
</pre>

<p>Hell, we can even set defaults for Model attributes by extending the object with <em>extend()</em>. This extends onto the Models prototype, the same formula for Collections and for Views.</p>

<pre class="prettyprint">var Item = Backbone.Model.extend({
  defaults: {
    price: 0.99
  }
});

// Default price for Item Model now 0.99
// If we do not set or define a price, it will result to this default,

var cabbage = new Item({ title: 'Cabbage' });

cabbage.get('price');
// =&gt; 0.99
</pre>

<h3>Collections</h3>

<p>As our bowels digest the Bacon and Cabbage, lets put their Models into a Collection. As I stated earlier, a Collection is a literal collection of Models that are relevant to one another. I created a Model in the example above called <strong>Item</strong> , now I want to make a collection to put all these Items together. It would be only fitting to name our Collection <strong>Items</strong>,</p>

<pre class="prettyprint">var Items = Backbone.Collection.extend({
  model: Item
});
</pre>

<p>We have created a new Collection called Items, and we have set its relational Model to Item, meaning we will only be putting Item Models in the Collection.</p>

<p>Assuming we have our two Item Models defined,</p>

<pre class="prettyprint">var bacon = new Item({ title: 'Bacon', price: 2.99 });
var cabbage = new Item({ title: 'Cabbage' });
</pre>

<p>Let us add them to Items,</p>

<pre class="prettyprint">// Define a new Collection of Items as itemColleciton
var itemCollection = new Items();

itemCollection.add( bacon );
itemCollection.add( cabbage );

itemCollection.length
// =&gt; 2

// bacon and cabbage are now in our Collection
</pre>

<p>Now that we have a Collection sailing about looking for Models, this can make the above processes a little easier. For instance, we can initialize a Collection and pass soon-to-be Models as arguments, like so,</p>

<pre class="prettyprint">// Assuming we have the Item Model and Items Collection defined

// Make an array of items instead of defining them individually as Models
var list = [
    { title: 'Bacon', price: 2.99 },
    { title: 'Cabbage' }
 ]

var itemCollection = new Items( list );

itemCollection.length
// =&gt; 2
</pre>

<p>Nice, we made two new Item Models and added them to Items at the same time. Instead of defining them individually, passing them through the Items constructor kills two birds with one array.</p>

<p><figure> 
<img src="http://duckbox.net/articles/resources/1/modelCollection.png" alt="Models &amp; Collections" /> 
<figcaption>Models &amp; Collections</figcaption> 
</figure></p>

<p>Now we should have a basic understanding of Collections and how they work with Models.</p>

<h3>Views</h3>

<p>Views are self-explanatory, the visual side of the app, the UI, the data rendered.</p>

<blockquote>
  <p>The general idea is to organise your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. </p><footer><span> Backbone.js on Views </span></footer>
</blockquote>

<p>We render our Models through a View, as our Model changes, so does our View.</p>

<pre class="prettyprint">var ItemView = Backbone.View.extend({

  // Our Views main container, which is a &lt;ul&gt; in the markup
  el: '#list',

  // Once this View is called, initialize is called
  initialize: function() {

    // We call this Views render function
    this.render();
  },

  render: function() {

    // We append this Models details to the Views container
    this.$el.append('&lt;li&gt;'+this.model.get('title')+
                    ' at '+this.model.get('price')+
                    '&lt;/li&gt;');
  }

});

// Define some Models
var bacon = new Item({ title: 'Bacon', price: 2.99 });
var cabbage = new Item({ title: 'Cabbage' });

// Make some new Views and pass in the Models
new ItemView({ model: bacon });
new ItemView({ model: cabbage });
</pre>

<p>On successfully creating these two Views and passing in our Models <em>bacon</em> and <em>cabbage</em>, we should end up with something like this,</p>

<pre class="prettyprint">&lt;ul id="list"&gt;
    &lt;li&gt;Bacon at 2.99&lt;/li&gt;
    &lt;li&gt;Cabbage at 0.99&lt;/li&gt;
&lt;/ul&gt;
</pre>

<p>This seems like a lot of unnecessary effort to do something so simple that can be done with jQuery in a few lines. Correct, but, if you did things that way, your application has no formal structure. Updating and scaling would eventually become a nightmare if you are coding a verbose application in this style. Whereas with Backbone, we have our data and our visual, separated.</p>

<p>Now, the above example was to demonstrate how a Backbone View works, whilst not being an ideal solution. The ItemView is a View for a single Model. Bacon has its own View, as does Cabbage.</p>

<p>Ideally in apps, we would want to create a main View, to hold the above Views.</p>

<p>In my next post we are going to create an application that lists several items that we would normally shop for. We would then select some of those items which we need to get at the shop, and they would appear in the shopping list. Whenever we have got said item, we would tick it as collected.</p>

<p>What we will be going through that we have not touched yet is the following,</p>

<ol>
   <li>Underscore Templates </li>
   <li>Fetching Model data from an extra source</li>
   <li>Working with Multiple Views</li>
   <li>Attaching events to our Views </li>
</ol>

<p>The Backbone documentation is very limited, but there are plenty of awesome resources and tutorials out there.</p>

<p>Any questions or complaints, you should hit me up on twitter.</p>
 
		<img src="http://feeds.feedburner.com/~r/duckboxblog/~4/ygC8dNpMLPk" height="1" width="1"/>]]></content:encoded>
	<guid isPermaLink="false">http://duckbox.net/kick-ass-with-backbone</guid>
	<feedburner:origLink>http://duckbox.net/kick-ass-with-backbone</feedburner:origLink></item>
	</channel>
</rss>
