<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Thieves Like Us]]></title><description><![CDATA[Opinions and code. But mostly opinions.]]></description><link>http://brianmajewski.com/</link><generator>Ghost 0.6</generator><lastBuildDate>Mon, 25 May 2026 20:23:50 GMT</lastBuildDate><atom:link href="http://brianmajewski.com/tag/requirejs/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[(Re)Learning Backbone Part 7]]></title><description><![CDATA[<p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/e55dbc2be4ab5e8ce883ad7e397654e346f5d135">e55dbc2be4ab5e8ce883ad7e397654e346f5d135</a>)</em></p>

<p><strong>Getting Our Users and Displaying Them</strong></p>

<p>Today, we are going to access our REST backend using Backbone's Collection object and display the results on screen. To do this, we'll add</p>]]></description><link>http://brianmajewski.com/2015/02/22/relearning-backbone-part-7/</link><guid isPermaLink="false">3ac3c9a9-ba7d-48c5-b617-0ff012ec5a4e</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[express]]></category><category><![CDATA[bower]]></category><category><![CDATA[requirejs]]></category><category><![CDATA[datatables]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sun, 22 Feb 2015 23:13:29 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/photo-1416339684178-3a239570f315.jpeg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/photo-1416339684178-3a239570f315.jpeg" alt="(Re)Learning Backbone Part 7"><p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/e55dbc2be4ab5e8ce883ad7e397654e346f5d135">e55dbc2be4ab5e8ce883ad7e397654e346f5d135</a>)</em></p>

<p><strong>Getting Our Users and Displaying Them</strong></p>

<p>Today, we are going to access our REST backend using Backbone's Collection object and display the results on screen. To do this, we'll add a link to our navigation section in the header, create a view to display the results, and update the router to include those results in our page layout.</p>

<p><strong>Navigation</strong></p>

<p>Let's go ahead and update <code>/app/page/header.hbs'</code>. Between the <code>navbar-header</code> div and the <code>navbar-right</code> div, add</p>

<pre><code class="language-markup">&lt;ul class="nav navbar-nav"&gt;  
    &lt;li&gt;&lt;a href="#users"&gt;&lt;span class="fa fa-users"&gt;&lt;/span&gt; Users&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;  
</code></pre>

<p>You'll notice there are some 'fa' classes in there. That's because I added <a href="http://fortawesome.github.io/Font-Awesome/">FontAwesome</a> to the mix. Use <strong>bower</strong> to install it</p>

<pre><code>bower install font-awesome --save  
</code></pre>

<p>then add the CSS to your index page  </p>

<pre><code class="language-markup">&lt;link rel="stylesheet" href="components/font-awesome/css/font-awesome.css"&gt;  
</code></pre>

<p>For our navigation, we used a standard A anchor tag with a URL that mimics our REST API URL. There is no technical need to keep them the same (and in fact they are not - our UI does not expose the <code>/api</code> portion) but keeping them aligned is a useful organizational tool. You should also notice that the URL begins with a hash. Backbone, by default, uses Hash URLs. They are more backwards compatible with older browsers that do not support Push State. Normal URLs are preferred and we'll convert this one later on to take advantage of them.</p>

<p><strong>Creating our Model and Collection</strong></p>

<p>Backbone provides some base objects that we can use to contain our model object (a User) and a collection of them. By giving these objects a URL, they will know how to interact with a standard REST API to retrieve and persist the objects. Let's create them now.</p>

<p><em>/app/users/model.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');

    return Backbone.Model.extend({
        idAttribute: '_id',
        urlRoot: '/api/users'
    });
});
</code></pre>

<p>Here we are setting two properties, <em>idAttribute</em>, which lets Backbone know to use the MongoDB generated value _id as the id for the object, and <em>urlRoot</em>, which tells it the base URL to use when constructing REST calls.</p>

<p><em>/app/users/collection.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var Model = require('users/model');

    return Backbone.Collection.extend({
        model: Model,
        url: '/api/users'
    });
});
</code></pre>

<p>Again, we are setting two properties. <em>model</em> is the Backbone model of the objects in the collection - in our case the User model. <em>url</em> is the REST API url to retrieve the collection from.</p>

<p><strong>Displaying The Collection</strong></p>

<p>In my apps, I have two different ways to think about displaying a collection of objects. In cases such as our User collection, it is primarily a tabular display of data. It can show all or a portion of the model's properties, and usually presents actions such as <strong>Edit</strong> or <strong>Delete</strong>. In cases such as these, I don't expect the collection to be changing underneath the user without explicit interaction. </p>

<p>Other collections, however, could be more dynamic. Suppose you are looking at a live stream of tweets that are getting continually updated. Perhaps the collection represent pieces in a game that are getting moved around based on rules. In cases like that, we will want to construct a collection view that delegates a lot of control to individual model views and can respond to events that they generate. </p>

<p>For <strong>CRUD</strong> screens like the one we are going to build, we can use the <a href="http://datatables.net/">DataTables</a> library to easily add features like sorting, pagination, and filtering to our view.</p>

<p>Install DataTables and a convenient plugin to mix it in with our Bootstrap theme:</p>

<pre><code>bower install datatables datatables-bootstrap3-plugin --save  
</code></pre>

<p>update <code>require-main.js</code> with the following entries</p>

<pre><code class="language-javascript">"datatables": "../components/datatables/media/js/jquery.dataTables",
"datatables-bootstrap3": 
    "../components/datatables-bootstrap3-plugin/media/js/datatables-bootstrap3"
</code></pre>

<p>and add the CSS to <code>index.html</code></p>

<pre><code class="language-markup">    &lt;link rel="stylesheet" href="components/datatables-bootstrap3-plugin/media/css/datatables-bootstrap3.css"&gt;
</code></pre>

<p>Now let's create our template and view</p>

<p><em>/app/users/list.hbs</em>  </p>

<pre><code class="language-markup">&lt;div class="well"&gt;  
    &lt;h4&gt;&lt;b&gt;Users&lt;/b&gt;&lt;/h4&gt;
&lt;/div&gt;  
&lt;table class="table table-bordered table-striped"&gt;  
    &lt;thead&gt;
    &lt;th&gt;ID&lt;/th&gt;
    &lt;th&gt;Email&lt;/th&gt;
    &lt;th&gt;Name&lt;/th&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
    {{#each users}}
        &lt;tr&gt;
            &lt;td&gt;{{_id}}&lt;/td&gt;
            &lt;td&gt;{{email}}&lt;/td&gt;
            &lt;td&gt;{{name}}&lt;/td&gt;
        &lt;/tr&gt;
    {{/each}}
    &lt;/tbody&gt;
&lt;/table&gt;  
</code></pre>

<p>A fairly straightforward table template. We'll use Handlebars #each directive to loop over the users and display a row for each.</p>

<p><em>/app/users/listView.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var template = require('hbs!users/list');
    require('datatables');
    require('datatables-bootstrap3');

    return Backbone.View.extend({
        el: '#content',
        render: function(){
            this.$el.html(template({users: this.collection.toJSON()}));
            this.$('table').DataTable();
            return this;
        }
    });

});
</code></pre>

<p>Some differences to call out. We've required our <em>DataTables</em> related libraries but did not assign them to a variable. Since they are plugins to jQuery, we won't need to access them on their own.</p>

<p>In our render method, we take our collection of users, convert them to JSON and pass that in as <em>users</em> to our template to render. This is the object that the #each directive is looping on in our template.</p>

<p>Finally, we activate the <em>DataTables</em> functionality by attaching it to the table in our view.</p>

<p>The only thing that may not be clear is where the collection we convert to JSON is coming from since we did not define it in this view. We could have instantiated it here, and asked it to fetch itself. We would then have to coordinate with our Page view to tell it that the collection was ready, and to rerender it. In some cases, such as when many different backend calls will need to be made to display a page, this will be an appropriate solution. For this simple case, we'll have the router grab the collection and prepare the view before we hand it off to the main Page. This way, it will be ready to render right away. Let's take a look at that:</p>

<p><em>/app/router.js</em>  </p>

<pre><code class="language-javascript">routes: {  
    '': 'home',
    'home': 'home',
    'users': 'users'
},

users: function() {  
    console.log('routing - users');
    require(['users/collection', 'users/listView'], function(Collection, View) {
        var collection = new Collection();
        collection.fetch().done(function(){
            mediator.trigger('page:displayView', new View({collection: collection}));
        });
    });
},
</code></pre>

<p>We've added a route for <code>users</code> that is handled by a <code>users</code> method and the <code>users</code> method itself. We require the users view and collection. We instantiate the collection and fetch the contents. When the contents are retrieved we add them a new view and send a message off to the page to render the view.</p>

<p><strong>Next Steps</strong></p>

<p>In the next installment, we'll some actions to add, edit, and delete users.</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 6]]></title><description><![CDATA[<p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/82df0f2fd5bdc91d5599aa1c40faacca38766327">82df0f2fd5bdc91d5599aa1c40faacca38766327</a>)</em></p>

<p><strong>Deep Breath</strong></p>

<p>This is going to be a lengthy installment. We've done a lot of setup, including creating a fully functioning server with REST endpoints and wiring up our front-end</p>]]></description><link>http://brianmajewski.com/2015/02/21/relearning-backbone-part-6/</link><guid isPermaLink="false">609e93e7-e0d7-42e1-9c80-bd0542c57c00</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[bower]]></category><category><![CDATA[requirejs]]></category><category><![CDATA[handlebars]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sun, 22 Feb 2015 00:14:37 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/laying_groundwork_wide.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/laying_groundwork_wide.jpg" alt="(Re)Learning Backbone Part 6"><p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/82df0f2fd5bdc91d5599aa1c40faacca38766327">82df0f2fd5bdc91d5599aa1c40faacca38766327</a>)</em></p>

<p><strong>Deep Breath</strong></p>

<p>This is going to be a lengthy installment. We've done a lot of setup, including creating a fully functioning server with REST endpoints and wiring up our front-end dependency management. Today, we are going to make a lot of small steps that when put together will give us a completely functional single page application with routing, an event bus, and dynamic views. Let's start by adding our third party dependencies.</p>

<p><strong>Bower</strong></p>

<p>We're going to be installing <a href="http://backbonejs.org">Backbone</a>, which has a dependency on <a href="http://underscorejs.org/">Underscore</a> and <a href="http://jquery.com/">jQuery</a>, for our MVC framework and <a href="http://handlebarsjs.com/">Handlebars</a> for our templating framework. We'll also be adding a <a href="https://github.com/requirejs/text">couple of plugins</a> for Require that will make <a href="https://github.com/SlexAxton/require-handlebars-plugin">loading our templates</a> easy.</p>

<p>To install the whole lot, run:</p>

<pre><code>bower install backbone underscore jquery handlebars requirejs-text require-handlebars-plugin --save  
</code></pre>

<p>When complete, you'll see your <code>bower.json</code> file has been updated and a bunch of new libraries has been installed under <code>public/components</code>. These libraries all have different directory structures and since they don't live under our <code>app</code> directory, we are going to create shortcuts for Require to use when loading them.</p>

<p>In our <code>require-main.js</code> file, add the following entries to the <em>paths</em> block;</p>

<pre><code class="language-javascript">paths: {  
    "jquery": "../components/jquery/dist/jquery",
    "underscore": "../components/underscore/underscore",
    "backbone": "../components/backbone/backbone",
    "handlebars": "../components/handlebars/handlebars.amd",
    "text": "../components/requirejs-text/text",
    "hbs": "../components/require-handlebars-plugin/hbs"
}
</code></pre>

<p>These are the paths to the main Javascript file in each of the libraries. You'll notice each is prefixed with <code>../</code>. This is because we set our <em>baseUrl</em> to <code>app</code>, so we need to adjust for that. We've also left the <code>.js</code> off the file name. If you look in the libraries, you'll see some come with pregenerated minified versions. At this point in development, I prefer using the full version to make debugging easier. We can worry about optimization later. Also note, we used the <code>.amd</code> version of Handlebars. This is the module format that Require uses so picking this flavor will let us work with it without having to create any shims.</p>

<p><strong>Routing and Our Home Page</strong></p>

<p>The heart of a single page application is the <a href="http://backbonejs.org/#Router">routing</a>. It is responsible for interpreting the URL and displaying the correct information on the screen. Later, it will also be responsible for ensuring that our user is authenticated and redirecting them to login if needed.</p>

<p>To begin, we are going to create a single route, that displays our main page layout. The layout will incorporate a container for sub-views to be displayed in and a header view to contain our navigation elements. We'll also use a partial template to display a footer at the bottom of our page. To help avoid memory leaks, we'll extend the standard Backbone <a href="http://backbonejs.org/#View">View</a> with some utility methods to clean itself up when it is closed.</p>

<p>All of these pieces are fairly intertwined so there is no obvious place to start. Let's start with a bit of plumbing that we will use throughout our whole app, our event bus.</p>

<p><strong>Event Bus</strong></p>

<p><a href="http://backbonejs.org/#Events">Backbone.Events</a> is a mixin that can be added to any object and enables that object to listen to and trigger events that other objects can listen for and react to. While, most Backbone objects have this mixin already, I find it is easier to create a specific object that we can explicitly use as an event bus.</p>

<p><em>/app/mediator.js</em>  </p>

<pre><code class="language-javascript">define(function(require){

    'use strict';

    var _ = require('underscore');
    var Backbone = require('backbone');

    return _.extend({}, Backbone.Events);

});
</code></pre>

<p>Simple really. We create an empty object, mixin the Events, and return it. Now, anywhere in our code we want to deal with messages, we can get a reference to this mediator and use it. There are some other interesting message patterns we may be interested in down the road, such as Commands and Requests. You can look at the <a href="https://github.com/marionettejs/backbone.radio">Backbone.Radio</a> plugin if your app needs these features.</p>

<p><strong>Home Page</strong></p>

<p>Create a <code>page</code> directory under <code>app</code> to hold the related files. We'll be using the '<a href="http://cball.me/organize-your-ember-app-with-pods/">pods</a>' method of organizing our files that has become popular with the Ember crowd. It will let us keep all the information for a given feature together, as opposed to organized by function(controllers, views, etc.).</p>

<p>Create the following files:</p>

<p><em>/app/page/pageTemplate.hbs</em></p>

<pre><code class="language-markup">&lt;div id="header"&gt;&lt;/div&gt;  
&lt;div id="content" class="container"&gt;&lt;/div&gt;  
&lt;div id="footer"&gt;{{&gt; ./footerTemplate}}&lt;/div&gt;  
</code></pre>

<p><em>/app/page/headerTemplate.hbs</em></p>

<pre><code class="language-markup">&lt;header&gt;  
    &lt;div class="navbar navbar-default"&gt;
        &lt;div class="container"&gt;
            &lt;div class="navbar-header"&gt;
                &lt;a href="/" class="navbar-brand"&gt;&lt;b&gt;relearning backbone&lt;/b&gt;&lt;/a&gt;
            &lt;/div&gt;
            &lt;ul class="nav navbar-nav navbar-right"&gt;
                [Navigation Elements]
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/header&gt;  
</code></pre>

<p><em>/app/page/footerTemplate.hbs</em></p>

<pre><code class="language-markup">&lt;div class="text-center"&gt;Relearning Backbone - http://brianmajewski.com&lt;/div&gt;  
</code></pre>

<p>In the main template, we define three divs that will contain our header, main content, and footer. Since the footer is going to be static content, we could have easily included it in the page but this is a way to validate that partial templates are being included.</p>

<p>For now, there is no functionality in the header, so let's create a very simple Backbone view that renders the template.</p>

<p><em>/app/page/headerView.js</em></p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';

    var Backbone = require('backbone');
    var template = require('hbs!page/headerTemplate');

    return Backbone.View.extend({
        el: '#header',

        render: function(){
            this.$el.html(template());
            return this;
        }
    });
});
</code></pre>

<p>There is that <code>define(function (require){});</code> syntax again. I always include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode"><code>'use strict';</code></a> as a matter of habit. Next, we use Require to include the Backbone library and the template. Note the syntax for the template: <code>hbs!page/headerTemplate</code> - <code>hbs!</code> tells require to use the <em>hbs</em> plugin we configured earlier, followed by the path to the template. It assumes a .hbs extension, but can be configured to accept others.</p>

<p>The rest is simple Backbone view stuff. We define the page element to attach the view to (<code>el: '#header'</code>), and then we define the render function, using the template as is to generate the html. As a matter of course, we will always return a reference to the view when we render it.</p>

<p>Now, let's create the containing Page view that will hold the header and other content views.</p>

<p><em>/app/page/pageView.hbs</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var mediator = require('mediator');
    var template = require('hbs!page/pageTemplate');
    var HeaderView = require('page/headerView');


    return Backbone.View.extend({
        el: '#page',

        initialize: function () {
            this.contentView = null;
            this.bindPageEvents();
        },

        render: function () {
            this.$el.html(template());
            this.headerView = new HeaderView();
            this.headerView.render();
            return this;
        },

        bindPageEvents: function () {
            mediator.on('page:displayView', this.displayView, this);
        },

        displayView: function (view) {
            if (this.contentView !== null) {
                this.contentView.close();
                this.contentView = null;
            }

            this.contentView = view;
            if (this.contentView) {
                this.contentView.render();
            }
        }
    });

});
</code></pre>

<p>This is very similar to the header. We set it's element to <code>#page</code>. In our <code>render</code> method, we instantiate the HeaderView and render it as well. In the <code>initialize</code> method, we create a variable to hold our content views, and set up the view to listen to messages. In <code>bindPageEvents</code>, we listen on the mediator for the message <code>page:displayView</code> and when we get it, we call the <code>displayView</code> method. Here, we clean up any existing content view and render the one passed to us with the message. One non-standard thing we are doing here is calling <code>.close</code> on the content view. Backbone has a <em>remove</em> method which does something similar but we are going to be a bit more aggressive in cleaning up our code. We'll add this code in when we update our <code>main.js</code> file.</p>

<p>To test this out, we need a content view. Go ahead and create the following files to provide a simple Welcome view.</p>

<p><em>/app/welcome/template.hbs</em>  </p>

<pre><code class="language-markup">&lt;div class="jumbotron"&gt;  
    &lt;h1&gt;WELCOME TO OUR APPLICATION&lt;/h1&gt;
&lt;/div&gt;  
</code></pre>

<p><em>/app/welcome/view.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var Backbone = require('backbone');
    var template = require('hbs!welcome/template');

    return Backbone.View.extend({
        el: '#content',
        render: function() {
            this.$el.html(template());
        }
    });

});
</code></pre>

<p>Now we need a way for the application to display this view when we start up the app. Let's go ahead and create our router.</p>

<p><em>/app/router.js</em>  </p>

<pre><code class="language-javascript">define(function (require) {

    'use strict';
    var mediator = require('mediator');
    var Backbone = require('backbone');
    var PageView = require('page/pageView');


    return Backbone.Router.extend({
        initialize: function () {
            this.pageView = new PageView();
            this.pageView.render();
            this.bindApplicationEvents();
        },

        routes: {
            '': 'home',
            'home': 'home'
        },

        home: function () {
            console.log('routing - home');
            require(['welcome/view'], function (View) {
                mediator.trigger('page:displayView', new View());
            });
        },

        bindApplicationEvents: function () {
            mediator.on('router:navigate', this._navigate, this);
        },

        _navigate: function (context) {
            console.log('routing - trigger to ', context.route);
            this.navigate(context.route, context.options);
        }
    });

});
</code></pre>

<p>Let's break this down in chunks.</p>

<p>In our <code>initialize</code> function, we instantiate our Page view and render it to the screen. At this point, it has its header and footer but its content view is empty. Our router will fill in different views based on the URLs we visit. We also tell it to <code>bindApplicationEvents</code>. You'll see this pattern repeated. I will have the initializer of a class setup the messages/event bus for the messages it is interested in receiving. In this case, we are listening for a <code>router:navigate</code> message. This will allow other parts of our application to change where we are in our app without having a direct reference to the router.</p>

<p>In our <code>routes</code> object, we set up two paths, <code>''</code> and <code>'home'</code> that will route us to the <code>home</code> function.</p>

<p>In our <code>home</code> function, we require our Welcome view, which is the content view we want to display when someone hits our home page, then fire off a message, with the view attached, that our page is listening for.</p>

<p><strong>Turning It On</strong></p>

<p>The last step we need to take is to turn on the router. Let's update our <code>main.js</code> file.</p>

<p><em>/app/main.js</em>  </p>

<pre><code class="language-lanaguage-javascript">define(function (require) {

    var Router = require('router');
    var mediator = require('mediator');

    var router = new Router();
    Backbone.history.start({pushState: false});

    if (Backbone.history.fragment === '') {
        mediator.trigger('router:navigate', {route: 'home', options: {trigger: true}});
    }
});
</code></pre>

<p>Here we simply instantiate our Router, and tell Backbone to start managing our history. We've also added a little helper to ensure that when a user comes in the first time, with no URL fragment, such as <code>/users/123</code>, that we send them to the home page.</p>

<p>Fire up the server and refresh your page. You should see our fully composed page.</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-21-at-4-01-31-PM.png" alt="(Re)Learning Backbone Part 6"></p>

<p><strong>Extending Backbone</strong> <br>
Remember, we wanted to add some functionality to ensure that Views we close release all their objects and events as to avoid memory leaks.</p>

<p>In our <code>main.js</code> file, under our require declarations, add the following code:</p>

<pre><code class="language-javascript">_.extend(Backbone.View.prototype, {  
        // Handle cleanup of view.
        close: function () {
            if (this.beforeClose) {
                // Perform any cleanup specific to this view.
                this.beforeClose();
            }

            if (this.model) {
                // Remove all callbacks for this view's model.
                this.model.off(null, null, this);
                this.model = null;
            }

            // Something else might be named 'collection' so also check for the
            // existence of `off`
            if (this.collection &amp;&amp; this.collection.off) {
                // Remove all callbacks for this view's collection.
                this.collection.off(null, null, this);
                this.collection = null;
            }

            // Remove all delegated events.
            this.undelegateEvents();
            this.off(null, null, this);

            // Remove all markup.
            this.$el.empty();
        }
    });
</code></pre>

<p>Here we extend the base View definition to add our <code>close</code> method. This will call a <code>beforeClose</code> method on a view, if it has one, for view specific cleanup. If the view has a model or collection associated with it, it turns off the model/collections's events and clears the model/collection. It then turns off the view's events and removes the contents from the DOM.</p>

<p><strong>Next Steps</strong></p>

<p>In our next installment, we'll create a view that retrieves our users from our REST backend and displays the results. </p>

<p><em>(The code at this state in the project can be checked out at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/e55dbc2be4ab5e8ce883ad7e397654e346f5d135">e55dbc2be4ab5e8ce883ad7e397654e346f5d135</a>)</em></p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 5]]></title><description><![CDATA[<p><em>(The current code base can be checked out <a href="https://github.com/bmajewski/relearning-backbone/commit/18b0d51ee45d966abf9293be9a5fe25c6af8c6a6">here</a>)</em></p>

<p><strong>Front End Build</strong></p>

<p>Often at this point in a project, I will get derailed. I'll start thinking about dependency management, should I use <a href="http://gruntjs.com/">Grunt</a> or <a href="http://gulpjs.com/">Gulp</a> or <a href="https://github.com/broccolijs/broccoli">Broccoli</a> or ... to build the project, module definitions, and the like. The combination of</p>]]></description><link>http://brianmajewski.com/2015/02/20/relearning-backbone-part-5/</link><guid isPermaLink="false">8f4b167f-9611-4b46-8bdd-efd5a3ebdacf</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[bower]]></category><category><![CDATA[requirejs]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sat, 21 Feb 2015 04:34:43 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/brown-paper-packages.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/brown-paper-packages.jpg" alt="(Re)Learning Backbone Part 5"><p><em>(The current code base can be checked out <a href="https://github.com/bmajewski/relearning-backbone/commit/18b0d51ee45d966abf9293be9a5fe25c6af8c6a6">here</a>)</em></p>

<p><strong>Front End Build</strong></p>

<p>Often at this point in a project, I will get derailed. I'll start thinking about dependency management, should I use <a href="http://gruntjs.com/">Grunt</a> or <a href="http://gulpjs.com/">Gulp</a> or <a href="https://github.com/broccolijs/broccoli">Broccoli</a> or ... to build the project, module definitions, and the like. The combination of all these options just multiplies and I'll spin until I lose interest in the project for awhile. </p>

<p>Tasks like minification and image optimization and static analysis are important parts of a production application but we still haven't written one line of front end code. In the spirit of XP, I did the <a href="http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork">simplest thing possible that still works</a>. </p>

<p>My requirements: I wanted to declare my Javascript dependencies on the fly. I always forget to add them individually to my index.html file. I want to declare them explicitly so that different sections of the code could be loaded independently when it comes time to optimize the app. This also has the side benefit of allowing my IDE to perform better autocompletion. I wanted all of my assets to be accessible  from the simple web server we created earlier without a separate deploy step. Once we have a working app, we can then go back and figure out how to serve up the bare minimum.</p>

<p>To accomplish all of these tasks, we are going to use two tools: <a href="http://bower.io/">Bower</a> and <a href="http://requirejs.org/">RequireJS</a>. Bower will handle the management of third-party libraries and RequireJS will handle our dependency management and loading of files. There are other options, especially for RequireJS, such as Browserify. Feel free to explore them and pick one you are comfortable. The way you modularize your code will be a part of every file you write, so be happy with your choice.</p>

<p><strong>Bower</strong></p>

<p>Bower, like Node's NPM, allows you to automatically retrieve libraries from the net, and manage them and their dependencies. To install it, run  </p>

<pre><code>npm install -g bower  
</code></pre>

<p>One quick customization we are going to make is where Bower stores its dependencies. Typically, we would keep them at the same level as our <code>node_modules</code> dependencies, and use a build tool to copy the specific JS and CSS files we need into our app. To avoid this, we will store our dependencies under our <code>public</code> directory so that our Node server can serve them up directly. This has the side effect that <em>ALL</em> files that come with the packages are accessible, such as READMEs and package files, but until we have a working app, this is a reasonable trade off. In your project directory, create a file called <code>.bowerrc</code> with the following contents:  </p>

<pre><code class="language-javascript">{
    "directory":"public/components"
}
</code></pre>

<p>With this complete, run bower init, answer the questions and finally end up with a <code>bower.json</code> file that looks similar to:  </p>

<pre><code class="language-javascript">{
  "name": "relearning-backbone",
  "version": "1.0.0",
  "homepage": "https://github.com/bmajewski/relearning-backbone",
  "authors": [
    "Brian M &lt;hireme@brianmajewski.com&gt;"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "public/components",
    "test",
    "tests"
  ]
}
</code></pre>

<p>We're now set up to use Bower to pull in our other dependencies, including RequireJS.</p>

<p><strong>RequireJS</strong></p>

<p>To effectively use RequireJS, you really should go and <a href="http://requirejs.org/docs/start.html">read through the docs</a> once or twice first. Go ahead, I'll wait. Done? Ok - It may not make a bunch of sense if you are new to this type of module management. Hopefully, as we work with it, it will become clearer.</p>

<p>In a nutshell, Require (I'm going to drop the JS from here on out) will allow us to specify just one Javascript requirement in our <code>index.html</code> file. From there out, it will dynamically load additional files as we need them without us having to explicitly add them.</p>

<p>To set this up, we'll update our <code>index.html</code> and create a configuration file for Require. To install Require, run:</p>

<pre><code> bower install requirejs --save
</code></pre>

<p>If you look under <code>public/components</code>, you'll see the newly installed package.</p>

<p>There are differing opinions on where to put Javascript declarations and how they effect initial download and rendering of your home page. For simplicity, we'll place our declaration in the <code>&lt;head&gt;</code> of our document, beneath our styles.</p>

<pre><code class="language-markup">&lt;head lang="en"&gt;  
    &lt;base href="/"&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Relearning Backbone&lt;/title&gt;
    &lt;link rel="stylesheet" href="assets/css/styles.css"&gt;
    &lt;script src="components/requirejs/require.js" data-main="require-main.js"&gt;&lt;/script&gt;
&lt;/head&gt;  
</code></pre>

<p>As you can see, we've added a non-standard attribute to our script tag: <code>data-main="require-main.js"</code>. This tells Require where to read its configuration information.</p>

<p>Go ahead and create the file <code>require-main.js</code> under <code>public</code>, with the following contents:</p>

<pre><code class="language-javascript">requirejs.config({  
    baseUrl: "app",

    paths: {

    }
});

require(['main']);  
</code></pre>

<p>This is (almost) as minimal of a config file we can use and have it still be useful. At the top, we call config on requirejs and set some properties. <em>baseUrl</em> is where require should look for all files we haven't explicitly defined. <em>paths</em> are those explicitly defined files (and is empty for now). Next, we invoke require with an array of files we need to load. Typically, you would declare those files, and then a function, assigning those files to variables, and do something with them, such as:</p>

<pre><code class="language-javascript">require(['moment'], function(moment){  
    moment.format();
});
</code></pre>

<p>which would load the <a href="http://momentjs.com/">Moment</a> library and display a formatted datestamp.</p>

<p>In this case, we are telling it to load the file <code>main</code> and process its contents. Our <code>main</code> file won't return anything - it will actually load up our application and start it up. Since we have't defined <code>main</code> in the <code>paths</code> block above, Require will look for <code>app/main.js</code>, so let's create an <code>app</code> directory and a <code>main.js</code> file with the following contents:</p>

<pre><code class="language-javascript">define(function (require) {  
    console.log('require module loading working');
});
</code></pre>

<p>All of our Javascript files will have this basic format: a define function that takes require as an argument. We'll be able to use this parameter later to load other files.</p>

<p>If you reload <code>index.html</code>, you should be able to see our message in your console window. This let's us know that we have Require wired in and loading our modules.</p>

<p><strong>Spit And Polish</strong></p>

<p>Before we get into the meat of designing our home page and screens to access the user data, I want to add a little bit of styling to the app. I find that if I leave things a little too "raw" I'll waste time trying to clean them up a bit. At this point I would usually grab <a href="http://getbootstrap.com/">Bootstrap</a> to provide a simple clean interface. But... should I use the plain CSS, or maybe the LESS or the SCSS... Do I need to add a CSS preprocessor to my build pipeline? What about all the Javascript components, should I add them in too? Will they conflict with the stuff I want to write later? Oh hey, what about trying <a href="http://susy.oddbird.net/">Susy</a> for a grid layout? And on and on it goes. Once again - <strong>DERAILED</strong> Here is what I do now. I go to <a href="http://bootswatch.com/">Bootswatch</a>, pick a color theme that I like in the moment, download the CSS file, put it in <code>assets/css</code>, add it to my <code>index.html</code> file and I am done with CSS until it comes time to actually build my app and its feature set.</p>

<p><strong>Next Steps</strong></p>

<p>With our package management and module loader in place, we're ready to start building out our client application. Next time, we'll create a simple router, a message bus, and main layout that will allow us to swap different content views in as needed.</p>

<p><em>(To grab the code at this point in the series, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/82df0f2fd5bdc91d5599aa1c40faacca38766327">82df0f2fd5bdc91d5599aa1c40faacca38766327</a> from <a href="https://github.com/bmajewski/relearning-backbone">Github</a>)</em></p>]]></content:encoded></item></channel></rss>