<?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 19:17:03 GMT</lastBuildDate><atom:link href="http://brianmajewski.com/tag/bower/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[(Re)Learning Backbone Part 8]]></title><description><![CDATA[<p>(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/c29507a245dce5f7cd3b900a72e8dbeac0fc3238">c29507a245dce5f7cd3b900a72e8dbeac0fc3238</a>)</p>

<p><strong>A Little Cleanup</strong></p>

<p>Back when we created the REST endpoints, we returned some "friendly" success messages. Without a UI, these made it easy to see when the requests went through.</p>]]></description><link>http://brianmajewski.com/2015/02/24/relearning-backbone-part-8/</link><guid isPermaLink="false">8a30c2da-9991-471c-a2e3-d2282ebf2ff3</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[node]]></category><category><![CDATA[bower]]></category><category><![CDATA[bootstrap]]></category><category><![CDATA[modal]]></category><category><![CDATA[data-binding]]></category><category><![CDATA[stickit]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Tue, 24 Feb 2015 05:02:02 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/oIpwxeeSPy1cnwYpqJ1w_Dufer-Collateral-test.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/oIpwxeeSPy1cnwYpqJ1w_Dufer-Collateral-test.jpg" alt="(Re)Learning Backbone Part 8"><p>(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/c29507a245dce5f7cd3b900a72e8dbeac0fc3238">c29507a245dce5f7cd3b900a72e8dbeac0fc3238</a>)</p>

<p><strong>A Little Cleanup</strong></p>

<p>Back when we created the REST endpoints, we returned some "friendly" success messages. Without a UI, these made it easy to see when the requests went through. Now that we are going to be using them, let's have them return something more useful.</p>

<p>For GET <code>/api/users</code> and GET <code>/api/users/:user_id</code>, we already return an array or a single user, as appropriate. Let's do the same for POST <code>/api/users</code> and PUT <code>/api/users/:user_id</code>. For these, we will return the User that was either just created or was updated. There is no user we can return after a DELETE, so we can return an empty object.  Our updated <code>/app/routes/user.js</code> code now looks like this:</p>

<pre><code class="language-javascript">var bodyParser = require('body-parser');  
var User = require('../models/user');

module.exports = function (app, express) {  
    var userRouter = express.Router();

    userRouter.get('/', function (req, res) {
        res.json({message: 'api is loaded'});
    });

    userRouter.route('/users')
        .post(function (req, res) {
            var user = new User();
            user.name = req.body.name;
            user.email = req.body.email;
            user.password = req.body.password;

            user.save(function (err) {
                if (err) {
                    if (err.code === 11000) {
                        return res.json({success: false, message: 'Duplicate username.'});
                    } else {
                        return res.send(err);
                    }
                } else {
                    res.json(user);
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });

    userRouter.route('/users/:user_id')
        .get(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);
                res.json(user);
            })
        })
        .put(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);

                if (req.body.name) user.name = req.body.name;
                if (req.body.email) user.email = req.body.email;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json(user);
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({});
            })
        });

    return userRouter;
};
</code></pre>

<p><strong>Adding Actions To Our User List</strong></p>

<p>We're going to want to be able to Add a User, and Delete or Edit a specific user. Let's start with Delete.</p>

<p>Let's add a column to our table on the right side to hold user specific actions. Add a blank <code>&lt;th&gt;&lt;/th&gt;</code> to our <code>&lt;thead&gt;</code> and a <code>&lt;td&gt;&lt;/td&gt;</code> in our <em>#each</em> loop. In the <code>&lt;td&gt;</code> add the following:</p>

<pre><code>&lt;button data-id="{{_id}}" class="btn btn-danger btn-sm js-deleteUser"&gt;Delete&lt;/button&gt;  
</code></pre>

<p>This will display a Delete button. We've added a <code>data=id</code> attribute to hold the User id. This will allow us to specify which User to delete. We've also added a <code>js-deleteUser</code> class to the button. We are using the <code>js-*</code> pattern for class names that indicate functionality as opposed to design.</p>

<p>Now, let's add the functionality to perform the delete in <code>/app/users/listView.js</code>. Under the <em>el</em> declaration, add an <em>events</em> block</p>

<pre><code class="language-javascript">events: {  
    'click .js-deleteUser': 'deleteUser'
},
</code></pre>

<p>On the left, we define an event and a CSS selector for the event, and on the right, a method to handle the event. In this case, we are trapping for a <em>click</em> event on any item with a class of <em>js-deleteUser</em>, and delegating to the <em>deleteUser</em> method to handle it. Let's create that method now.</p>

<pre><code class="language-javascript">deleteUser: function(e){  
    var self = this;
    var id = $(e.currentTarget).attr('data-id');
    var user = this.collection.get(id)
    user.destroy().done(function(){
        self.collection.remove(user);
        self.render();
    });
}
</code></pre>

<p>Here we ask the object that triggered the event for the value of its <em>data-id</em> attribute, and retrieve that user from our collection. We trigger the <em>destroy</em> method provided by Backbone, we will call our REST backend. When it is complete, we remove the user from the collection, and redraw the table.</p>

<p>Reload the app, and delete a user. If you don't have any to delete, you can either use the Postman extension to add some more, or, we can forge ahead and wire in an Add button.</p>

<p>We want to have a modal dialog popup with a form that will allow us to enter in a name, an email, and a password, along with a button to save it. With a little bit of configuration, we can use this same dialog to edit an existing user. To do the heavy lifting, we're going to add in a few libraries. Since we are using Bootstrap for our CSS, let's just dive in and grab the whole framework. We'll still only pull in what we need as we need it. We're also going to use a Backbone plugin to wrap the Bootstrap modal functionality so that we can easily interact with it from our views. Adding <a href="https://github.com/powmedia/backbone.bootstrap-modal">backbone.bootstrap-modal</a> with bower will pull both libraries in. </p>

<p>We also want to incorporate data-binding. Data-binding is one of the <strong>big</strong> features that frameworks like Angular and Ember pitch as a benefit. We're going to get all the functionality they provide with much greater and explicit control of when we use binding and how for a lighter footprint on our page. For this, we will use <a href="http://nytimes.github.io/backbone.stickit/">stickit</a> from the NYTimes. Install both these libraries with</p>

<pre><code>bower install backbone.bootstrap-modal backbone.stickit --save  
</code></pre>

<p>and update the <code>require-main.js</code> file</p>

<pre><code class="language-javascript">"bootstrap-modal": "../components/bootstrap/js/modal",
"backbone.bootstrap-modal": "../components/backbone.bootstrap-modal/src/backbone.bootstrap-modal",
"stickit" : "../components/backbone.stickit/backbone.stickit"
</code></pre>

<p>Let's once again update our list view, with an Add button at the top of the page and an Edit button next to the Delete.</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;span class="pull-right"&gt;&lt;button class="btn btn-primary js-editUser"&gt;Add User&lt;/button&gt;&lt;/span&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;th&gt;&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;td&gt;
                &lt;div class="pull-right"&gt;
                    &lt;button data-id="{{_id}}" class="btn btn-danger btn-sm js-deleteUser"&gt;Delete&lt;/button&gt;
                    &lt;button data-id="{{_id}}" class="btn btn-success btn-sm js-editUser"&gt;Edit&lt;/button&gt;
                &lt;/div&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    {{/each}}
    &lt;/tbody&gt;
&lt;/table&gt;  
</code></pre>

<p>Since we are using the same code for both editing and adding, we've added the same class, <em>js-editUser</em> to both. To the Edit button, we add a <em>data-id</em> attribute. If we were going to add any more actions, we might consider putting the ID on the row once for all the fields. For now, we'll stick with this.</p>

<p>Let's update our List view to trap for the new event.</p>

<pre><code class="language-javascript">events: {  
    'click .js-deleteUser': 'deleteUser',
    'click .js-editUser': 'editUser'
},
</code></pre>

<p>and</p>

<pre><code class="language-javascript">editUser: function(e) {  
    var id = $(e.currentTarget).attr('data-id');
    var options = id ? {title: 'Edit User', model: this.collection.get(id)} : {title: 'Add User'};
    console.log('options', options);
}
</code></pre>

<p>We don't have anywhere to send the user just yet, so we'll construct our options and log them to verify our event is wired in. Here we check for a <em>data-id</em> value on the element. If we have one, we are going to edit the user, so we set an appropriate title for our soon to be created dialog, and retrieve the user from the collection. If there is no <em>data-id</em>, like on the Add button, we set the title to 'Add User', and leave the model undefined. Reload your app and verify that we have all this working.</p>

<p><strong>Creating our Dialog</strong></p>

<p>Whether we are adding or editing a User, we will need a form with fields to enter data. Let's create a template for one, wrapped in the markup to create a Bootstrap modal dialog.</p>

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

<pre><code class="language-markup">&lt;div class="modal-dialog"&gt;  
    &lt;div class="modal-content"&gt;
        &lt;div class="modal-header"&gt;
            &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt;
            &lt;h4 class="modal-title"&gt;&lt;b&gt;{{title}}&lt;/b&gt;&lt;/h4&gt;
        &lt;/div&gt;
        &lt;div class="modal-body"&gt;
            &lt;form class="form-horizontal"&gt;
                &lt;div class="form-group"&gt;
                    &lt;label for="email" class="col-lg-2 control-label"&gt;Email&lt;/label&gt;

                    &lt;div class="col-lg-10"&gt;
                        &lt;input type="text" class="form-control" id="email" placeholder="Email"&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;label for="name" class="col-lg-2 control-label"&gt;Name&lt;/label&gt;

                    &lt;div class="col-lg-10"&gt;
                        &lt;input type="text" class="form-control" id="name" placeholder="Name"&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;label for="password" class="col-lg-2 control-label"&gt;Password&lt;/label&gt;

                    &lt;div class="col-lg-10"&gt;
                        &lt;input type="password" class="form-control" id="password" placeholder="Password"&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/form&gt;
        &lt;/div&gt;
        &lt;div class="modal-footer"&gt;
            &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt;
            &lt;button type="button" class="btn btn-primary js-saveUser"&gt;Save changes&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;  
</code></pre>

<p>This is mostly boilerplate Bootstrap code. Notice that we have assigned IDs to the form fields. We will use these to bind our data. Because we are binding our data, we don't need to use any template substitution for these values. We have also added a variable to hold our <em>title</em> at the top, and we added a <em>js-saveUser</em> class to our <strong>Save</strong> button. We'll use Bootstrap's built in functionality to cancel/close the modal when the user hits the Cancel or Close buttons.</p>

<p>To pair with our template, we will create a simple Backbone view. This view will handle binding our model data to the form fields and vice versa. It will also persist the data when the <strong>Save</strong> button is pressed.</p>

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

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

    'use strict';
    var Backbone = require('backbone');
    var mediator = require('mediator');
    var template = require('hbs!users/single');

    require('stickit');

    var User = require('users/model');

    return Backbone.View.extend({
        initialize: function (options) {
            this.title = options ? options.title : 'Please Set A Title';
            this.model = this.model || new User();
        },

        bindings: {
            '#name': 'name',
            '#email': 'email',
            '#password': 'password'
        },

        events: {
            'click .js-saveUser': 'saveUser'
        },

        render: function () {
            this.$el.html(template({title: this.title}));
            this.stickit();
            return this;
        },

        saveUser: function () {
            var self = this;
            this.model.save().done(function (response) {
                if (self.model.isNew()) {
                    self.model.set('_id', response._id);
                }
                mediator.trigger('users:userSaved', self.model);
            });
        }
    });

});
</code></pre>

<p>At the top, we require our dependencies. We also include <em>stickit</em> here. Since it is a plugin, we don't need to assign it to anything. In our <em>initialize</em> method, we set some default values if the options passed to us don't have them. We also create a new User if we need one, as is the case for when we are adding one.</p>

<p>The <em>bindings</em> block is new. This is how we configure <em>stickit</em>. In this simple example, we map our CSS selectors on the right to User model attributes on the left. Stickit can do a lot more than this so read the docs.</p>

<p>We set up a standard <em>events</em> entry to trap for the <strong>Save</strong> button.</p>

<p>In our <em>render</em> method, we render our template as normal, then call stickit to activate the bindings.</p>

<p>Finally, we create a <em>saveUser</em> method. We use Backbone's built in save functionality. This will determine if the User is new or being edited, and call the appropriate backend method. When we get a successful response, we update our object with an _id value if necessary, then fire off a message to let our list view know we are done. We do this so that the list view can manage the lifecycle of the dialog window, including the opening and closing of it.</p>

<p>Let's now go back to our list view and update it to manage the dialog window.</p>

<p>Add our new dependencies  </p>

<pre><code class="language-javascript">var mediator = require('mediator');  
var SingleView = require('users/singleView');  
require('bootstrap-modal');  
require('backbone.bootstrap-modal');  
</code></pre>

<p>Since we are going to be responding to message, let's wire that up:  </p>

<pre><code class="language-javascript">initialize: function(){  
    this.bindPageEvents();
},

bindPageEvents: function(){  
    mediator.on('users:userSaved', this.userSaved, this);
},

userSaved: function(user){  
    this.modal.close();
    this.collection.add(user);
    this.render();
}
</code></pre>

<p>When we receive a message that the user has been saved, we close the modal that we will soon create, add the passed user to our collection, and rerender the table. If the user has an id that is already part of our collection, it will update itself, otherwise it will add itself.</p>

<p>Finally, lets create the modal. Let's go back to our <em>editUser</em> method</p>

<pre><code class="language-javascript">editUser: function(e) {  
    var id = $(e.currentTarget).attr('data-id');
    var options = id ? {title: 'Edit User', model: this.collection.get(id)} : {title: 'Add User'};
    var modalView = new SingleView(options);
    this.modal = new Backbone.BootstrapModal({content: modalView}).open();
},
</code></pre>

<p>We've removed the logging. We instantiate the view that holds our form fields with the options we've created. We then wrap that view with a Backbone.BootstrapModal view and open it. Simple as that. Reload your app and try adding and editing some Users.</p>

<p>Let's make one final cosmetic tweak. Since the last column in the table is always the same visually, let's turn sorting off for it. Pass in the following options when we construct the DataTable</p>

<pre><code class="language-javascript">this.$('table').DataTable({  
    "aoColumns": [
        null,
        null,
        null,
        { "bSortable": false }
    ]
});
</code></pre>

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

<p>We now have a relatively full featured CRUD management tool. We could easily add new entities by following the patterns we have set up here. Could we have generated these much quicker with an all encompassing framework? Sure. The use of small focused plugins, however, has kept our boilerplate code to a minimum and we have had full control over every line of code.</p>

<p>The last big piece that we are going to add that I consider mandatory for a starter app is <strong>authentication</strong>. We will put all the User editing functionality behind a login screen and see how to hold and use application wide data, such as the currently logged in user.</p>

<p>(The code at this state in the project can be checked out at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/8a19651c576968b29f143d271147b0b288ca63a7">8a19651c576968b29f143d271147b0b288ca63a7</a>)</p>]]></content:encoded></item><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>