<?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>Wed, 08 Apr 2026 06:13:50 GMT</lastBuildDate><atom:link href="http://brianmajewski.com/tag/javascript/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[(Re)Learning Backbone Part 12]]></title><description><![CDATA[<p><strong>Permissions</strong> <br>
For the last piece of our application, we are going to require that a user have "admin" permissions to delete another user. We created a cheat way to add permissions to our users earlier in the series. Using that, or Mongohub, ensure we have one user with "admin" as</p>]]></description><link>http://brianmajewski.com/2015/03/06/relearning-backbone-part-12/</link><guid isPermaLink="false">aca10dc4-ffec-4b56-8a3f-73503c232f98</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[node]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 06 Mar 2015 05:14:49 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/03/Fuyu_Persimmon_-Diospyros_Kaki-.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/03/Fuyu_Persimmon_-Diospyros_Kaki-.jpg" alt="(Re)Learning Backbone Part 12"><p><strong>Permissions</strong> <br>
For the last piece of our application, we are going to require that a user have "admin" permissions to delete another user. We created a cheat way to add permissions to our users earlier in the series. Using that, or Mongohub, ensure we have one user with "admin" as a permission, and one user without. Let's start logged in as the user <em>without</em> permissions.</p>

<p><strong>Update The Server</strong></p>

<p>On the server, we know who the user making a request is due to the token they present on every call, but we don't have the User object. We could make a DB call to see if they have the right permissions. This could become a burden on our server. We could use a server side session to store the User, but again, this may not scale well. The easiest way to determine the permissions is to have the user tell us. We can add the permissions to the token before we encrypt it. Then when we decrypt it, which we do on every authenticated call, we can access the permissions it contains.  Let's update our <code>authenticate</code> endpoint</p>

<p><em>/app/routes/user.js</em>  </p>

<pre><code class="language-javascript">userRouter.post('/authenticate', function (req, res) {  
    User.findOne({
        email: req.body.email
    }).select('name email password').exec(function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'User not found'});
        } else {
            var validPassword = user.comparePassword(req.body.password);
            if (!validPassword) {
                res.json({success: false, message: 'Wrong password'});
            } else {
                var token = jwt.sign({
                    name: user.name,
                    email: user.email,
                    _id: user._id,
                    permissions: user.permissions
                }, superSecret, {
                    expiresInMinutes: 1440
                });

                res.json({
                    success: true,
                    message: 'login ok',
                    token: token,
                    _id: user._id
                });
            }
        }
    });
});
</code></pre>

<p>We simply added the one line</p>

<pre><code>permissions: user.permissions  
</code></pre>

<p>in our signing method.</p>

<p>Now, let's update our DELETE route to check for admin. For convenience, and consistency with our client, let's throw <a href="http://underscorejs.org/">underscore.js</a> into the server.</p>

<pre><code>npm install underscore --save  
</code></pre>

<p>and add it to the top of our user routes</p>

<pre><code>var _ = require('underscore');  
</code></pre>

<p>and finally update the DELETE route</p>

<pre><code class="language-javascript">.delete(function (req, res) {
    if (_.contains(req.decoded.permissions, 'admin')){
        User.remove({_id: req.params.user_id}, function (err, user) {
            if (err) res.send(err);
                res.json({});
            })
        } else {
            return res.status(403).send({success: false, message: 'User is not authorized to delete users'});
        }
    });
</code></pre>

<p>We check if the permissions property of our decoded token contains "admin", and if not, throw a 403 error. Refresh the server and try to delete a user. You should see the error in the console window and the list of users remaining the same.</p>

<p>For this error, we don't want to redirect the user anywhere but it would be nice to let them know that the error occured.  Let's trap for the 403, like we did the 401, and popup an alert. For our popups, we'll be using <a href="https://github.com/CodeSeven/toastr">Toastr</a>, so let's add it with bower, update <code>require-main.js</code>, and include its CSS on our index page.</p>

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

<p><em>require-main.js</em>  </p>

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

    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",
        "datatables": "../components/datatables/media/js/jquery.dataTables",
        "datatables-bootstrap3": "../components/datatables-bootstrap3-plugin/media/js/datatables-bootstrap3",
        "bootstrap-modal": "../components/bootstrap/js/modal",
        "backbone.bootstrap-modal": "../components/backbone.bootstrap-modal/src/backbone.bootstrap-modal",
        "stickit" : "../components/backbone.stickit/backbone.stickit",
        "toastr" : "../components/toastr/toastr"
    }
});

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

<p><em>index.html</em>  </p>

<pre><code>&lt;link rel="stylesheet" href="components/toastr/toastr.css"&gt;  
</code></pre>

<p>With the library in place, let's update our error handler. Remember to require toastr at the top of the file.</p>

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

<pre><code class="language-javascript">$.ajaxSetup({
    statusCode: {
        401: function (context) {
            mediator.trigger('router:navigate', {route: 'login', options: {trigger: true}});
        },

        403: function(context){
            toastr.options = {
                "closeButton": false,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };

            toastr["error"](context.responseJSON.message);
        }
    },
    beforeSend: function (xhr) {
        var token = window.localStorage.getItem(globals.auth.TOKEN_KEY);
        xhr.setRequestHeader('x-access-token', token);
    }
});
</code></pre>

<p>You can configure your popup however you like. These options are the ones generated from the library's demo site. We configure the popup, then display the error message our backend returned to us.</p>

<p>One last tweak is needed. Backbone is optimistic when you ask to destroy a model, and will remove it from any collections it is in. Since we may not want that to happen, we pass in a <em>wait</em> property to our <em>destroy</em> method. Let's update that</p>

<p><em>app/users/listView.js</em>  </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({wait: true}).done(function(){
        self.collection.remove(user);
        self.render();
    });
}
</code></pre>

<p>Now, ideally, we don't want the user to even be given the option to press the delete button. All of this error handling is neccesary to protect our data but we shouldn't be giving users options they don't have. Much like checking for authentication, we are going to create a way for our views to check for authorizations.</p>

<p>Let's create a simple Permissions object that we can create when the user logs in.</p>

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

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

    'use strict';

    var _ = require('underscore');

    return function(permissions){
        this.isAdmin = function(){
            return _.contains(permissions, 'admin');
        };
    }
});
</code></pre>

<p>We'll pass in the permissions array from the user when we create this, then for convenience we expose an <em>isAdmin</em> function. This can be expanded as needed. Common patterns include 'has one of these permissions' and 'has all of these permissions'. Let's update our <code>app</code> object</p>

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

<pre><code class="language-javascript">var Permissions = require('permissions');  
var _permissions;

function _initializeUser() {  
    var d = $.Deferred();
    if (_isAuthenticated() &amp;&amp; !_user) {
        _user = new User({_id: window.localStorage.getItem(globals.auth.USER_KEY)});
        _user.fetch().success(function () {
            mediator.trigger('page:updateUserInfo');
            _permissions = new Permissions(_user.get('permissions'));
            d.resolve();
        });
    } else {
        d.resolve();
    }
    return d.promise();
}

function _getPermissions() {  
    return _permissions;
}

return {  
    isAuthenticated: _isAuthenticated,
    initialize: _initialize,
    initializeUser: _initializeUser,
    getApplicationInfo: _getApplicationInfo,
    getUser: _getUser,
    getPermissions: _getPermissions
}
</code></pre>

<p>Now, let's update our user list template and view to not show the delete button unless the user is an admin.</p>

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

<pre><code class="language-markup">&lt;div class="pull-right"&gt;  
    &lt;button data-id="{{_id}}" class="btn btn-danger btn-sm js-deleteUser"&gt;Delete&lt;/button&gt;
    {{#if ../admin}}&lt;button data-id="{{_id}}" class="btn btn-success btn-sm js-editUser"&gt;Edit&lt;/button&gt;{{/if}}
&lt;/div&gt;  
</code></pre>

<p>Here we check the value of <em>../admin</em> to conditionally show the button. We are using the <code>../</code> notation because we are inside of the <code>users</code> loop and we will be storing our admin value one level up.</p>

<p><em>_app/users/listView.js (render)</em>  </p>

<pre><code class="language-javascript">render: function () {  
    this.$el.html(template({
        users: this.collection.toJSON(), 
        admin: app.getPermissions().isAdmin() 
    }));
    this.$('table').DataTable({
        "aoColumns": [
            null,
            null,
            null,
            { "bSortable": false }
        ]
    });
return this;  
}
</code></pre>

<p>After adding an app dependency to our object, we add an <em>admin</em> value to the context object we pass our template for rendering. Refresh the page, and the button is gone. Log in now as a user with admin permissions and verify that the button is still visible and in fact deletes the user.</p>

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

<p>In our final installment, we will make a few tweaks to the code and talk about what could be some next steps.</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/7d3bc57ffc8ec09c4e28b739da9ba3d20da37a2c">7d3bc57ffc8ec09c4e28b739da9ba3d20da37a2c</a>)</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 11]]></title><description><![CDATA[<p><strong>A Little Clean Up</strong></p>

<p>At this point, we have a fairly functional app, with full CRUD operations and an authentication strategy. Before we dive into doing authorization, or permission based access, we are going to clean up our app logic a little bit, proactively protect our routes from unauthorized access,</p>]]></description><link>http://brianmajewski.com/2015/03/05/relearning-backbone-part-11/</link><guid isPermaLink="false">455cb99a-4895-44ba-ba4a-fc1a5aa4ae3f</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 06 Mar 2015 01:32:22 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/03/Agriplus.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/03/Agriplus.jpg" alt="(Re)Learning Backbone Part 11"><p><strong>A Little Clean Up</strong></p>

<p>At this point, we have a fairly functional app, with full CRUD operations and an authentication strategy. Before we dive into doing authorization, or permission based access, we are going to clean up our app logic a little bit, proactively protect our routes from unauthorized access, get a reference to the currently logged in user, and display relevant information in the header.</p>

<p>For the most part, we access data when we need it. Some data, however, is global and used by the app as a whole. This could be information such as an application version or build information. It could be reference data used in most pages, or, in our case, it's the user that is currently logged in.  We're going to create an <code>app</code> object that will hold on to these types of values. It will also handle orchestrating information and workflow between views when appropriate.</p>

<p>We'll start by moving our local storage access routines into it.</p>

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

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

    'use strict';

    var globals = require('globals');
    var mediator = require('mediator');

    function _authenticated(response) {
        window.localStorage.setItem(globals.auth.TOKEN_KEY, response.token);
        window.localStorage.setItem(globals.auth.USER_KEY, response._id);
        mediator.trigger('router:navigate', {route: 'home', options: {trigger: true}});
    }

    function _logout(){
        window.localStorage.removeItem(globals.auth.TOKEN_KEY);
        window.localStorage.removeItem(globals.auth.USER_KEY);
        mediator.trigger('router:navigate', {route: 'home', options: {trigger: true}});
    }

    mediator.on('app:authenticated', _authenticated, this);
    mediator.on('app:logout', _logout);

    return {

    }

});
</code></pre>

<p>We pull in our <em>globals</em> and <em>mediator</em> objects, and set up two functions that are called when the appropriate messages are triggered. Now, we can clean up <code>/app/router.js</code> and <code>/app/login/view.js</code>, removing their local storage calls and redirects with a simple message. To ensure that this global object is always loaded and listening for messages, we can load it along with the main file in <code>require-main.js</code></p>

<pre><code class="language-javascript">require(['main', 'app']);  
</code></pre>

<p><strong>Protecting Our Routes</strong></p>

<p>We'll be adding to <code>app.js</code> shortly. Let's look at how we can enhance our router to protect our routes from unauthorized access. It's important to remember - <strong>ALL THIS CODE IS CLIENT SIDE</strong> - when we say we are protecting it, all we are doing is providing a better experience for our users and, in this case, minimizing the number of unauthenticated service calls. Any data, images, etc. that is in your JS/Handlebars/whatever files will still be sent to the user's browser - especially after you concatenate them.</p>

<p>If you recall the flowchart from the last installment, we asked potentially three questions before sending a user to their requested route: Does the route need authentication, do we have a stored token, and do we have a stored User? The first question we will answer implicitly by guarding only the routes that need it. For our app, that would be the Users page. The second question we will ask explicitly in our router, directing the user to a login page if not already authenticated. The third question we will defer to the view that we will use the information in.</p>

<p>Here is our new <code>users</code> route in our router:</p>

<pre><code class="language-javascript">users: function() {  
    console.log('routing - users');
    if (app.isAuthenticated()) {
        require(['users/collection', 'users/listView'], function (Collection, View) {
            var collection = new Collection();
            collection.fetch().done(function () {
                mediator.trigger('page:displayView', new View({collection: collection}));
            });
        });
    } else {
        console.log('unauthenticated - redirecting to login');
        this.login();
    }
},
</code></pre>

<p>We've wrapped our regular routing code in a check to our app object to see if we are authenticated, and if not we go to the login page. So, let's add that code now. On the empty object we are currently exporting from <em>app</em> we'll add an <em>isAuthenticated</em> property which will hold a reference to a "private" function.</p>

<pre><code class="language-javascript">function _isAuthenticated(){  
    return window.localStorage.getItem(globals.auth.TOKEN_KEY);
}

return {  
    isAuthenticated: _isAuthenticated
}
</code></pre>

<p>Here we are simply returning the value of the token we have stored. We make the assumption if there is one, it is valid, and use the truthiness of the value as our answer. If we want to get fancy, we could decouple this even more, using a Request pattern. Check out <a href="https://github.com/marionettejs/backbone.radio">Backbone.Radio</a> for more info.</p>

<p>Will the stored token always be valid? No. We currently have ours set to expire after 24 hours but nothing is going to remove it from the browser's storage unless the user logs out. In this case, we fall back on our 401 error handling. Same goes for a token that is forged or otherwise malformed. We could get fancy and use a client side JSON Web Token library to verify the encryption signature but there's really no need. </p>

<p><strong>Application Wide Data</strong></p>

<p>In addition to our current user, let's set up an unauthenticated API call that returns the current version of our application. Typically, we would set up another set of routes for our server, but let's cheat and put this call in our <em>user</em> routes. Use the following code and place it <strong>before</strong> we apply our authentication middleware.</p>

<pre><code class="language-javascript">userRouter.get('/applicationInfo', function(req,res){  
    res.json({version: '1.0-apple', build: 'local'});
});
</code></pre>

<p>While we are at it, let's add that URL to our <code>globals</code> object</p>

<pre><code class="language-javascript">urls: {  
    AUTHENTICATE: '/api/authenticate',
    APP_INFO: '/applicationInfo'
}
</code></pre>

<p>Together with the current user, we are going to spruce up our header/footer areas. So, we will be answering that third question (Do we have a user/app wide data?) in our page view. We will ask for it when we first render our page. In addition, we will add some messaging so that we can update our page should the information change (such as when the user logouts).</p>

<p>Since this is the third question, we can assume the user is authenticated - we verified this with the second question. What we can't assume is that we've loaded this information already. Perhaps the user is returning after being gone awhile. They still have a valid token, so they are 'authenticated' but haven't retrieved the requested data. What we want to do is "always" get the data, and then when done, return to our view. I say "always" because we will do a quick check and only call the server if we don't have it. To accomplish this, we will use jQuery's <a href="http://api.jquery.com/category/deferred-object/">Deferred object and promises</a>. In the case that the user has <em>not</em> authenticated, we will return an empty user object and render our page accordingly.</p>

<p><em>Aside: One might wonder why we don't store this information like we do the token or user id. For one, this type of information, especially reference data, can get quite large. We want to limit the amount of data we store locally. Additionally, this data can change. Maybe not over the course of a user's session but we do want to ensure we are working with current data when possible. Finally, some of the information may be sensitive. Leaving it in the browser storage makes it accessible with little safeguards.</em></p>

<p><strong>Updating Our Header</strong></p>

<p>Let's update the header to show different information on whether or not we have a valid user object. Let's assume if we have an empty user object (no <em>_id</em> property) that there is no logged in user.</p>

<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"&gt;
                {{#if _id}}
                    &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;
                {{/if}}
            &lt;/ul&gt;
            &lt;ul class="nav navbar-nav navbar-right"&gt;
                {{#if _id}}
                    &lt;li class="navbar-text"&gt;Hello {{name}}&lt;/li&gt;
                    &lt;li&gt;&lt;a href="#logout"&gt;Logout &lt;span class="fa fa-lg fa-sign-out"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
                {{else}}
                    &lt;li&gt;&lt;a href="#login"&gt;Login &lt;span class="fa fa-lg fa-sign-in"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
                {{/if}}
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/header&gt;  
</code></pre>

<p>To see this in action, we can update the render methods in our header view and page view</p>

<p><em>/app/page/headerView.js (render)</em>  </p>

<pre><code class="language-javascript">render: function(){  
    this.$el.html(template(this.model.toJSON()));
    return this;
}
</code></pre>

<p><em>/app/page/pageView.js (render)</em>  </p>

<pre><code class="language-javascript">render: function () {  
    this.$el.html(template());
    //this.headerView = new HeaderView({ model: new User() });
    this.headerView = new HeaderView({ model: new User({ _id: '1', email: 'a@example.com', name: 'Example User' })});
    this.headerView.render();
    return this;
}
</code></pre>

<p>Here we alternately bind an empty User to the header view's model or one we mocked up. Comment one or the other out to see the two states of the header.</p>

<p>With that working, let's update our page view render once again to work with real live data. <br>
<em>/app/page/pageView.js (render)</em>  </p>

<pre><code class="language-javascript">render: function () {  
    var self = this;
    // Gets nonauthenticated application info
    app.initialize().done(function () { 
        // Ensure user is loaded if authenticated or blank user if not
        app.initializeUser().done(function(){ 
            self.$el.html(template());
            self.headerView = new HeaderView({ model: app.getUser()});
            self.headerView.render();
            return self;
        });
    });
}
</code></pre>

<p>Here we've wrapped our rendering with two asynchronous calls to load app data and the current user, and we get the current user (or a blank one) to bind to the header view's model. Let's add these three methods to our app object (and a fourth for getApplicationInfo which we will use later).</p>

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

<pre><code class="language-javascript">// other methods above

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

function _initialize() {  
    var d = $.Deferred();
    if (_applicationInfo !== null) {
        d.resolve();
    } else {
        $.ajax({
            url: globals.urls.APP_INFO,
            success: function (data) {
                _applicationInfo = data;
                d.resolve();
            }
        });
    }
    return d.promise();
}

function _initializeUser() {  
    var d = $.Deferred();
    if (_isAuthenticated() &amp;&amp; !_user) {
        _user = new User({_id: window.localStorage.getItem(globals.auth.USER_KEY)});
        _user.fetch().success(function () {
            d.resolve();
        });
    } else {
        d.resolve();
    }
    return d.promise();
}

function _getApplicationInfo() {  
    return _applicationInfo;
}

function _getUser() {  
    return _user || new User();
}

return {  
    isAuthenticated: _isAuthenticated,
    initialize: _initialize,
    initializeUser: _initializeUser,
    getApplicationInfo: _getApplicationInfo,
    getUser: _getUser
}
</code></pre>

<p>This works. Kind of. If you already have a token from logging on previously, when you refresh the page, you should see the correct information in the header. However, if you need to login first, or when your log out, you'll see that the header information never changes. We set it once when we rendered it and then leave it alone. We need for our page view to respond when ever our current user changes.</p>

<p>Let's look at logout first. Let's update our <code>logout</code> method in <code>app</code> to clear out our user and fire off a message</p>

<pre><code class="language-javascript">function _logout() {  
    window.localStorage.removeItem(globals.AUTH_TOKEN_KEY);
    window.localStorage.removeItem(globals.AUTH_USER_KEY);
    _user = null;
    mediator.trigger('page:updateUserInfo');
    mediator.trigger('router:navigate', {route:'home', options: {trigger: true}});
};
</code></pre>

<p>Now, let's have the header view respond to that message. Here is the new view</p>

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

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

    'use strict';

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

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

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

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

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

        updateUserInfo: function(){
            this.model = app.getUser();
            this.render();
        }
    });
});
</code></pre>

<p>Now, when we logout, the header refreshes itself and clears the user's info. Now for logging in. Previously on login, we stored the token and user id and then navigated to the home page. Let's also load up the user with our <code>_initializeUser</code> call and send a message to update the page when it's done.</p>

<pre><code class="language-javascript">function _authenticated(response) {  
    window.localStorage.setItem(globals.auth.TOKEN_KEY, response.token);
    window.localStorage.setItem(globals.auth.USER_KEY, response._id);
    _initializeUser();
    mediator.trigger('router:navigate', {route: 'home', options: {trigger: true}});
}

function _initializeUser() {  
    var d = $.Deferred();
    if (_isAuthenticated() &amp;&amp; !_user) {
        _user = new User({_id: window.localStorage.getItem(globals.auth.USER_KEY)});
        _user.fetch().success(function () {
            mediator.trigger('page:updateUserInfo');
            d.resolve();
        });
    } else {
        d.resolve();
    }
    return d.promise();
}
</code></pre>

<p>Once again, when the message is fired, the header view will be updated. We can follow the same pattern for any data that is stored and updated away from the view that is displaying it. </p>

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

<p>The last piece of functionality we want to take a look at is authorization. Just because a user is logged in doesn't mean they have access to all the app's features. We'll look at allowing only certain users to use the <em>Delete</em> feature and handling 403 Unauthorized errors.</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/5942747fa9d760d148e825c76df05a6b8ea81c00">5942747fa9d760d148e825c76df05a6b8ea81c00</a>)</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 10]]></title><description><![CDATA[<p><strong>Logging In</strong></p>

<p>When we last left off, we had enforced authentication on our <code>users</code> endpoints and provided an endpoint to authenticate against. Today, we are going to add a Login screen and route to present our credentials to the backend. Upon success, we'll store the returned token and present it</p>]]></description><link>http://brianmajewski.com/2015/03/03/relearning-backbone-part-10/</link><guid isPermaLink="false">fba991ee-c41d-4fa5-8755-101d041ff747</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[node]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Wed, 04 Mar 2015 01:47:29 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/free_login_sign_up_buttons_by_button_finder-d4pyzqo.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/free_login_sign_up_buttons_by_button_finder-d4pyzqo.jpg" alt="(Re)Learning Backbone Part 10"><p><strong>Logging In</strong></p>

<p>When we last left off, we had enforced authentication on our <code>users</code> endpoints and provided an endpoint to authenticate against. Today, we are going to add a Login screen and route to present our credentials to the backend. Upon success, we'll store the returned token and present it on all subsequent requests.</p>

<p>Let's start by introducing a <code>globals</code> object. I like to create an object to hang constant values off of that are needed throughout the app.</p>

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

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

    'use strict';

    return {
        auth: {
            TOKEN_KEY: 'authToken',
            USER_KEY: 'userId'
        },
        urls: {
            AUTHENTICATE: '/api/authenticate'
        }
    }
});
</code></pre>

<p>Here we've defined two keys we are going to use to store and retrieve authentication data and the URL we need to hit to authenticate. For entities, like <em>User</em>, we store the URL with the model, but for URLs that don't neatly map to a model, I like to keep them here in globals.</p>

<p>So, with our authentication in place, if we try to hit <code>/#users</code>, we'll get a 401 error when we call the <code>/api/users</code> endpoint, and our screen will only show our header and our footer. Let's have our app respond to 401 errors by redirecting the user to a login screen.</p>

<p>In <code>/app/main.js</code>, before we create our Router, add the following code:</p>

<pre><code class="language-javascript">$.ajaxSetup({
    statusCode: {
        401: function () {
            console.log('AJAX Handler - 401 Error Received');
            mediator.trigger('router:navigate', {route: 'login', options: {trigger: true}});
        }
    }
});
</code></pre>

<p>We are using jQuery to make a global change to our AJAX handling. Now, any AJAX call that gets a 401 error will get trapped and we'll trigger the router to take us to our login page. Let's update our router to handle this.</p>

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

login: function() {  
    console.log('routing - login');
    require(['login/view'], function(View){
        mediator.trigger('page:displayView', new View());
    });
}
</code></pre>

<p>We've updated our route table to include a login path, and created a handler for it. This should seem familiar by now. We'll need a template and a view.</p>

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

<pre><code class="language-markup">&lt;div class="well"&gt;  
    &lt;h4&gt;&lt;b&gt;Login&lt;/b&gt;&lt;/h4&gt;
&lt;/div&gt;  
&lt;div class="alert alert-warning" style="display: none;"&gt;&lt;/div&gt;  
&lt;form class="form-horizontal login-form"&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="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;button type="button" class="btn btn-primary js-login pull-right"&gt;Login&lt;/button&gt;
&lt;/form&gt;  
</code></pre>

<p>This is a simple form that will allow us to collect an email address and a password. It also has an <em>alert</em> div we will use to display error messages and a submit button with the class <code>js-login</code> which will trigger the submission action.</p>

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

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

    'use strict';

    var Backbone = require('backbone');
    var globals = require('globals');
    var mediator = require('mediator');
    var template = require('hbs!login/template');

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

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

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

        login: function (e) {
            e.preventDefault();
            var formValues = {
                email: this.$('#email').val(),
                password: this.$('#password').val()
            };
            this.$('.alert').hide();
            console.log('login with ', formValues);
            $.ajax({
                url: globals.urls.AUTHENTICATE,
                type: 'POST',
                dataType: 'json',
                data: formValues,
                success: function(response){
                    if (response.success){
                        window.localStorage.setItem(globals.auth.TOKEN_KEY, response.token);
                        window.localStorage.setItem(globals.auth.USER_KEY, response._id);
                        mediator.trigger('router:navigate', {route:'home', options: {trigger: true}});
                    } else {
                        self.$('.alert-warning').text(response.message).show();
                    }
                }
            });
        }
    });
});
</code></pre>

<p>This is a standard view that listens for a click event on our submit button. When it receives one, we go to the <em>login</em> method.</p>

<p>Here, we get the values from the form fields. If the alert box is visible, we hide it. Finally, we make an AJAX call to our authentication endpoint, using the URL we defined in our globals. </p>

<p>If you remember, our authentication routine does not send back an HTTP error code. This allows us to handle any errors here. In our case, the <em>else</em> block, when the response message <em>success</em> property is false, takes the message returned from the server, adds it to the alert box and makes it visible.</p>

<p>When we successfully enter our credentials, we use local storage to store the auth token and the user id that was returned to us. Finally, we navigate to the home screen. Later, we can add code to redirect the user to their original destination but for now, we'll go home.</p>

<p>So what happens if we try to go to <code>/#users</code> again. Another 401 error! Just because we logged in once, the server has no idea that it is still us unless we tell it. To do this, we will include that token we just received in the header of all our AJAX calls. Go back to where we trapped for the 401 error and update the handler</p>

<pre><code class="language-javascript">$.ajaxSetup({
    statusCode: {
        401: function (context) {
            mediator.trigger('router:navigate', {route: 'login', options: {trigger: true}});
        }
    },
       beforeSend: function (xhr) {
        var token = window.localStorage.getItem(globals.auth.TOKEN_KEY);
        xhr.setRequestHeader('x-access-token', token);
    }
});
</code></pre>

<p>We've added the <em>beforeSend</em> method. This will retrieve the token from local storage, and set the <em>x-access-token</em> header to that value. If you recall, that is where our authenticated routes look for the token when determining if the caller is authenticated. Now if we hit our users page, the token we previously stored will be sent with our call, we'll be authenticated, and the page will display properly.</p>

<p>If you need to try again, you can use your browser's dev tools to remove the token from local storage, effectively logging you out. Let's make this a little easier on ourselves. Later, we'll be customizing our header view with information specific to the current user. For now, let's add a <em>logout</em> link.</p>

<p>In <code>/page/headerTemplate.hbs</code> replace the <code>[Navigation Elements]</code> place holder with</p>

<pre><code class="language-markup">&lt;li&gt;&lt;a href="#logout"&gt;&lt;span class="fa fa-lg fa-times-circle-o"&gt;&lt;/span&gt; Logout&lt;/a&gt;&lt;/li&gt;  
</code></pre>

<p>and update your router</p>

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

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

logout: function() {  
    window.localStorage.removeItem(globals.auth.TOKEN_KEY);
    window.localStorage.removeItem(globals.auth.USER_KEY);    
    this.home();
 }
</code></pre>

<p>This simply deletes our authentication info and sends the user to the home page. If it seems a little messy that we are messing with local storage in different parts of our app, you're right. Later when we coordinate loading the currently authenticated user, we'll create some convenience methods that we can trigger with messages through the mediator.</p>

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

<p>When we load our app, we will want to make sure we have the user object associated with the currently logged in user. We've already stored the id, so it is just a matter of loading the user. With that User, we'll customize the header. Additionally, we relied on the 401 error to redirect us to the login page. We'll be adding an <em>isAuthenticated</em> check to the router itself so that we can redirect to the login screen without needing to make a server call round trip.</p>

<p><em>(You can check out the project at it's current state at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/8a0a2b3c06575454a7ffae2b03b579d3bc47acba">8a0a2b3c06575454a7ffae2b03b579d3bc47acba</a>)</em></p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 9]]></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/8a19651c576968b29f143d271147b0b288ca63a7">8a19651c576968b29f143d271147b0b288ca63a7</a>)</em></p>

<p><strong>Authentication and Authorization</strong></p>

<p>In this installment we'll tackle some functionality that I feel many tutorials leave out - authentication. We are going to implement a simple model that will both</p>]]></description><link>http://brianmajewski.com/2015/02/25/relearning-backbone-part-9/</link><guid isPermaLink="false">979665a2-f68d-4037-99ee-83f2e1cec6ab</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[json web tokens]]></category><category><![CDATA[bcrypt]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Thu, 26 Feb 2015 04:53:11 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/risk-based-authentication1.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/risk-based-authentication1.jpg" alt="(Re)Learning Backbone Part 9"><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/8a19651c576968b29f143d271147b0b288ca63a7">8a19651c576968b29f143d271147b0b288ca63a7</a>)</em></p>

<p><strong>Authentication and Authorization</strong></p>

<p>In this installment we'll tackle some functionality that I feel many tutorials leave out - authentication. We are going to implement a simple model that will both authenticate users and determine whether they are authorized to perform a function.  This implementation is not meant to be bulletproof but to get a basic workflow in place. We'll be identifying a user as an admin with permissions to delete users. In practice, I usually keep all admin type functions out of my main application. Keeping them to themselves in a purpose built app allows you to restrict the audience and enforce other security measures, such as IP whitelisting.</p>

<p>HTTP is a stateless transaction by default. Whether we create a server side session to track user details or not, we need some way to identify an incoming request as being made by a particular user. We will be using <a href="http://jwt.io/">JSON Web Tokens</a> to provide this identification. They will be generated by our server when a user authenticates themselves and stored in the browser's local storage. To demonstrate authorization and personalizing the interface we will also be asking the server for the user information for the currently logged in user and a set of permissions for actions they are allowed to take. We will use these permissions on the client to present a better experience for the user; we won't easily allow them to perform an action they are not authorized to perform. Ultimately, all actions will be verified on the server to prevent users from bypassing our UI restrictions.</p>

<p>Before we get into the code, let's take a look at the workflow of authenticating a user. Let's assume we have a home page accessible to anyone, our users page, accessible to logged in users, and the delete button accessible to anyone with Admin permissions.</p>

<p>We can describe our workflow in two places: the router and application wide AJAX error handling.</p>

<p>Here is the logic workflow we will be implementing in the router and supporting classes:</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/router_flowchart-1.gif" alt="(Re)Learning Backbone Part 9"></p>

<p>Along with these decisions, we will intercept and handle the following HTTP error codes returned by our backend:</p>

<dl>  
<dt>401</dt><dd>The User is not Authenticated - Redirect to Login</dd>  
<dt>403</dt><dd>The User is not Authorized - Redirect to Home</dd>  
<dt>500</dt><dd>Generic Error Handling</dd>  
</dl>

<p>So, in the case that a user has a token, but it has expired, when they go to retrieve their User object, we will return a 401 error, forcing them to login.</p>

<p><strong>Creating An Admin User (The Wrong Way)</strong></p>

<p>We don't want to create a full featured permissions model or management console at this point. We haven't coded any features so trying to write permissions would be premature. It would be helpful for testing and prototyping, however, to indicate that one or more of our users had a specific property. To add these permissions to a user, we are going to cheat. For our POST <code>/api/users</code> and PUT <code>/api/users/:user_id</code> routes, we are going to check the request query parameters. Any parameters that match <code>permission=foo</code> will get added to a permissions block on the user. If there are none, the permissions block will be set to empty. We will also want to update our User schema to return these permissions as part of our normal retrieval functionality.</p>

<p><em>/app/models/user.js</em>  </p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Schema = mongoose.Schema;


var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false},
    permissions: [String]
});

module.exports = mongoose.model('User', UserSchema);  
</code></pre>

<p>Here we simply added an Array of Strings named <em>permissions</em> to the Schema.</p>

<p>And update the POST and PUT blocks in <code>/app/routes/user.js</code> to include  </p>

<pre><code class="language-javascript">user.permissions = req.query.permissions || [];  
</code></pre>

<p>where we set the other user properties. Now, using our Postman utility, create or update an existing user and some permissions to the url. For example:</p>

<pre><code>localhost:1337/api/users/54ea3206488bfd24c5ac7ee8?permissions=admin&amp;permissions=superhero  
</code></pre>

<p>This would then add <code>admin</code> and <code>superhero</code> to our permissions array. If we leave them off, an empty array is used. Again, this is <strong><em>The Wrong Way</em></strong> to do this, but it will serve our purposes.</p>

<p><strong>Changes</strong></p>

<p>So, let's run down the code changes we are going to make</p>

<ul>
<li><p>We are going to modify our backend server code and</p>

<ul><li>create an <code>/api/authenticate</code> endpoint that will accept credentials. If successful, it will return a token.</li>
<li>modify the <code>/api/user(s)</code> endpoints to check for the presence of a valid token before performing any actions. If one is not found, a 401 Unauthenticated error code will be returned.</li>
<li>modify the DELETE <code>/api/users/:user_id</code> endpoint to verify the authenticated user also has admin permissions. If not, a 403 Unauthorized error code will be returned.</li>
<li>update our server to accept requests from other domains. <em>(More on this later)</em>. 
<p></p></li></ul></li>
<li><p>We will create a login screen and</p>

<ul><li>extend the existing single user form view</li>
<li>add some simple client side validation to enforce name and email requirements</li>
<li>call the authentication endpoint</li>
<li>upon successful login we'll store the token received <br>
<p></p></li></ul></li>
<li><p>We will create a logout action in our navigation bar that</p>

<ul><li>will be visible only when logged in</li>
<li>will remove the stored token when activated
<p>  </p></li></ul></li>
<li>We will display information about the logged in user in the navigation bar
<p>  </p></li>
<li><p>We will modify our router to</p>

<ul><li>ensure that we are authenticated before showing the Users view
<p></p></li></ul></li>
<li><p>We will create an application wide object to</p>

<ul><li>perform authentication and logout actions</li>
<li>provide access to our currently logged in user
<p>  </p></li></ul></li>
<li>We will add application wide AJAX error handling</li>
</ul>

<p><strong>Server Updates</strong></p>

<p><em>Authentication Endpoint</em> - Until now, we've been storing our passwords in the database in  cleartext. We should really be encrypting them. Let's grab a <a href="https://www.npmjs.com/package/bcrypt-nodejs">crypto library</a> to handle that, along with the JSON Web Tokens library.</p>

<pre><code>npm install bcrypt-nodejs jsonwebtoken --save  
</code></pre>

<p>In <code>/app/models/user.js</code> let's go ahead and require the crypto library and add some functionality to use it.</p>

<pre><code class="language-javascript">var bcrypt = require('bcrypt-nodejs');

UserSchema.pre('save', function(next){  
    var user = this;
    if (!user.isModified()){
        return next();
    }

    bcrypt.hash(user.password, null, null, function(err,hash){
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

UserSchema.methods.comparePassword = function(password){  
    var user = this;
    return bcrypt.compareSync(password, user.password);
};
</code></pre>

<p>We have two things going on here. First, we've added a hook to the User schema that will get called before any Save operation. If the document has been modified, or is new, we assume the password has been modified and is in cleartext. We convert it to an encrypted form, and then let the normal save function occur.</p>

<p>Secondly, we've added a <code>comparePassword</code> method to the User object. When we authenticate a user, we will use this compare the submitted password to the stored one.</p>

<p>Now let's update our user routes in <code>/app/routes/user.js</code>. First add our dependency:</p>

<pre><code class="language-javascript">var jwt = require('jsonwebtoken');

var superSecret = 'TheAmazingKreskin`;  
</code></pre>

<p>We've also created a "secret word" that we will use when encrypting and decrypting our token. This should probably be stored in a config file or passed in on the command line for better security. </p>

<p>After our default <code>/api/</code> route, let's create our <code>/api/authenticate</code> route</p>

<pre><code class="language-javascript">var userRouter = express.Router();

userRouter.post('/authenticate', function (req, res) {  
    User.findOne({
        email: req.body.email
    }).select('name email password').exec(function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'User not found'});
        } else {
            var validPassword = user.comparePassword(req.body.password);
            if (!validPassword) {
                res.json({success: false, message: 'Wrong password'});
            } else {
                var token = jwt.sign({
                    name: user.name,
                    email: user.email,
                    _id: user._id
                }, superSecret, {
                    expiresInMinutes: 1440
                });

                res.json({
                    success: true,
                    message: 'login ok',
                    token: token,
                    _id: user._id
                });
            }
        }
    });
});

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

<p>When receive the POST request, we lookup the user by the provided email, and select their name and password as well. Remember, by default, our Schema does not return a password. In the event of an error or the user is not found, an error is returned to the user. In this instance, we don't send an error response. We expect that an unsuccessful attempt is a common occurrence, so we will explicitly handle the response. In this way, we could count the number of attempts or provide extra help, rather than just redirecting back to the login page.</p>

<p>If the user is found, we compare the submitted password to the one on record. If successful, we create a token with some user info in it and a timeout of 1440 minutes, or 24 hours. This will force the user to reauthenticate after one day, even if they have a proper token. Encrypting it will prevent the token from being modified by the client.</p>

<p>Using our Postman extension, we can test this endpoint right away. Using our prvious user editing capabilities, change the password on one of the users. This will ensure that the password associated with the user is encrypted in the database. (In fact, you may want to clean out any other users you created since they will need to have their passwords reset. For a production app, we could trap for this condition and handle it gracefully. Let's just delete them and make new ones.)</p>

<p>Make a POST request to <code>/api/authenticate</code> with a body of  </p>

<pre><code>{"email" : "email_value", "password": "password_value"}
</code></pre>

<p>using the values for that user you updated. Remember to set the Content-Type header to <code>application/json</code>. If the passwords match, you should see a response similar to</p>

<pre><code class="language-javascript">{
    "success": true,
    "message": "login ok",
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQnJpYW4gTSIsIl9pZCI6IjU0ZTZiMTYyZWIyYWM2MWM1NGU5YjgwZiIsImlhdCI6MTQyNDkyNTA4MCwiZXhwIjoxNDI1MDExNDgwfQ.90utguKl1XrpQZHU6tYPzOhskOeSl4k5RTTk6JcbuDo",
    "_id": "54e6b162eb2ac61c54e9b80f"
}
</code></pre>

<p>Even with our authentication endpoint in place, we have no problem accessing our app, even if we provided the wrong password. We'll need to tell the other routes to check for a valid token to be sent with every request.</p>

<p>After our default route, add the following code. Since this is declared <em>after</em> the default route, we will still be able to access it without authentication.</p>

<pre><code class="language-javascript">userRouter.get('/', function (req, res) {  
    res.json({message: 'api is loaded'});
});

userRouter.use(function (req, res, next) {  
    var token = req.body.token || req.params.token || req.headers['x-access-token'];
    if (token) {
        jwt.verify(token, superSecret, function (err, decoded) {
            if (err) {
                return res.status(401).send({success: false, message: 'Failed to authenticate token'});
            } else {
                req.decoded = decoded;
                next();
            }
        })
    } else {
        return res.status(401).send({success: false, message: 'No token provided'});
    }
});
</code></pre>

<p>With the <em>use</em> directive, we are adding some middleware to our route. For every request on routes declared after this we will attempt to find a token value in the body, in the parameters, or even in the headers. If a token is found, we verify it with our secret word. If it is valid, we continue to the <em>next</em> request handler, which will be our standard GET, PUT, POST, etc. calls. If there is no token, or it is invalid, we send a 401 HTTP error with an appropriate message. Our client will know that it needs to reauthenticate when it receives such a message.</p>

<p>Now, if we try to access our users page, we will get an error and nothing will display. </p>

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

<p>In our next installment, we'll wire up the client to call the authenticate endpoint when needed and send our token on future calls.</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/dae2b441bf1c718a6000df50679a6b096d70d8c4">dae2b441bf1c718a6000df50679a6b096d70d8c4</a>)</p>]]></content:encoded></item><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><item><title><![CDATA[(Re)Learning Backbone Part 4]]></title><description><![CDATA[<p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and</p>]]></description><link>http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/</link><guid isPermaLink="false">6735c52a-db17-41c0-a71f-1fe0a8ccfa47</guid><category><![CDATA[javascript]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[node]]></category><category><![CDATA[express]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[postman]]></category><category><![CDATA[crud]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 20 Feb 2015 04:17:04 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" alt="(Re)Learning Backbone Part 4"><p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and timeouts to simulate connection delays. If you know what you're doing, these can be a quick way to get a screen or feature running. If you're building from the ground up, you're just delaying the inevitable. Plus, if you've never done it before, figuring out how to wire it in later can be a challenge.</p>

<p><strong>MongoDB and mongoose</strong></p>

<p>Earlier in this series we installed <a href="http://www.mongodb.org/">MongoDB</a>. Ensure that you have a running copy before continuing. For a GUI front end, I like using <a href="https://github.com/jeromelebel/MongoHub-Mac">MongoHub</a>. <a href="http://mongoosejs.com/">Mongoose</a> is an object modeling solution that lets you write simple schema based objects to work between your Node server and your Mongo database. It has hooks for validation, query building and more, and with a healthy plugin ecosystem can do nearly anything you throw at it. We'll only scratch the surface of its feature set.</p>

<p>To install mongoose, run:</p>

<pre><code>npm install mongoose --save  
</code></pre>

<p>We'll need to tell our app how to connect to MongoDB. In our <code>server.js</code> file, add  </p>

<pre><code>var mongoose = require('mongoose');  
</code></pre>

<p>to the dependencies section at the top. Then underneath that, add  </p>

<pre><code>mongoose.connect('mongodb://localhost:27017/rlbb');  
</code></pre>

<p>If you configured MongoDB to run on another port, edit the above the string. <code>rlbb</code> is the name of our database and will be created if not present. Here is also where we would add things like database username, password, and the like if we had them.</p>

<p>Now, let's create a User model. Under <code>app/models</code>, create <code>user.js</code></p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Schema = mongoose.Schema;

var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false}
});

module.exports = mongoose.model('User', UserSchema);  
</code></pre>

<p>Here, we've pulled in our mongoose dependency and created a User Schema object. Mongoose uses the Schema as representation of a MongoDB collection and the base of its functionality. We've defined a <strong>name</strong>, an <strong>email</strong>, and a <strong>password</strong>. Along with the property names, we've defined their <em>SchemaType</em>, in this case, they are all Strings. For email and password, we've also included some additional properties. <em>required</em> indicates that the field must be present to be valid. Other validators include <em>min</em>, <em>max</em>, <em>match</em>, and custom validators can be created. For email, which we will use as our username, we create an index for it, and put a <em>unique</em> constraint on it. For password, we indicate that normal retrieval of this object from the collection should <em>not</em> include the password field. This prevents it from going across the network. When we add authentication later, we will explicitly ask for the password. Finally, we create a mongoose model from the schema and export it.</p>

<p><strong>Our First REST Endpoints</strong></p>

<p>So, we have a model of our User data. We now need a way to retrieve it from and write it to the database. In this app, all of our API URLs will start with <code>/api/</code> and then follow with the appropriate REST endpoints. For user, we will end up creating:  </p>

<dl>  
    <dt>/api/users</dt>
    <dd>POST - With a POST request, a new user will be created.<br>
    GET - With a GET request, this will return all users.
    </dd>

    <dt>/api/users/:user_id</dt>
    <dd>GET - With a GET request, this will return a single user with an ID that matches <i>:user_id</i>.<br>
    PUT - With a PUT request, the user indicated will be updated.<br>
    DELETE - With a DELETE request, the user indicated will be deleted.</dd>
</dl>

<p>With just two endpoints, and using the HTTP verbs, we can satisfy our basic CRUD requirements. To define these, we will create an Express router and then have Express <em>use</em> it, much like we did with the static assets directory and the catch all request handler.</p>

<p>Under <code>app/routes</code>, create <code>user.js</code> <sup id="fnref:1"><a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fn:1" rel="footnote">1</a></sup>.</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.username = req.body.username;
            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({message: 'user created'});
                }

            });
        })
        .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({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });

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

<p>This looks like a lot, but it's fairly straightforward. Let's tackle it a chunk at a time.</p>

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

<p>Here will pull in our dependencies. We will use <em>body-parser</em> to get the data that comes with the PUT and POST requests and <em>User</em> is the user model we just created.</p>

<pre><code class="language-javascript">    var userRouter = express.Router();

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

<p>Here we create an instance of an Express router. To give us a way to verify our routes have been initialized properly, we create a default route <code>api/</code> that will respond with a canned message. If there are problems we can use this to see if it is a server or database issue.</p>

<pre><code class="language-javascript">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({message: 'user created'});
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });
</code></pre>

<p>Here we create the <code>api/users</code> route and handle both the POST and the GET cases. In the POST block, we create a new User, set the fields with data from the request body, and save it. Mongoose handles the heavy lifting of creating the query and talking to the database. We perform some basic error-handling, and return an appropriate message to the client.</p>

<p>In the GET block, we call a static model method on User to retrieve all the stored users and return them. Once again, mongoose takes care of the details.</p>

<pre><code class="language-javascript">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.username) user.username = req.body.username;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });
</code></pre>

<p>Here we create the <code>api/users/:user_id</code> route. Express will take the value in the request that maps to the <code>:user_id</code> section and create a request parameter that we can use. In the GET block, we use mongoose's <em>findById</em> method to retrieve a specific user. In the PUT block, we again retrieve the requested user, update its information with data from the request body, then save it. Finally, in the DELETE block, we use mongoose's <em>remove</em> function to delete the specified user.</p>

<p>Now it's time to wire the router into the server. In <code>server.js</code>, <strong>after</strong> the static directory declaration, add the following</p>

<pre><code class="language-javascript">// already in our file
app.use(express.static(__dirname + '/public'));

// ADD THESE TWO LINES
var userRoutes = require('./app/routes/user')(app, express);  
app.use('/api', userRoutes);

// already in our file
app.get('*', function(req,res){  
    res.sendFile(path.join(__dirname + '/public/index.html'));
});
</code></pre>

<p>First we create the routes, by requiring the file and passing it the two needed fields, app and express. (Go back and look at how we declared our router definition and you will see we have these two params listed). Then, we tell our server to <em>use</em> the routes. Remember, order is important. First our static files, then our API routes, and finally the catch all to serve up our home page. If we added our routes after the catch all, they would never be hit.</p>

<p>If we were to run our server now, with <code>nodemon server.js</code> we would be able to get and set users via HTTP. But... we don't have any users yet, and we don't have screens to input data. Any easy solution is to use something like <a href="https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm/related?hl=en">Postman - REST Client for Chrome</a> (all the browsers have similar tools). In the URL field, enter <code>localhost:1337/api</code> and make sure GET is selected in the dropdown. When you hit send, you should see our test message returned in JSON format. </p>

<p>We can do a similar task to add a user. Set the URL to <code>localhost:1337/api/users</code>, the method to POST, select <code>raw</code> for our input data and add</p>

<pre><code>{ "email" : "hireme@brianmajewski.com", name: "Brian M", password: "123456Secure!"}
</code></pre>

<p>These are the fields we defined on our User model.</p>

<p>We also need to set our content type, so select Headers, and for name put <code>Content-Type</code> and value put <code>application/json</code>. If we're configured right, you should get a response back saying user created. To see our new user, hit the same URL, with GET, and you should receive a response similar to</p>

<pre><code>[
    {
        "_id": "54e6b162eb2ac61c54e9b80f",
        "email": "hireme@brianmajewski.com",
        "name": "Brian M",
        "__v": 0
    }
]
</code></pre>

<p>Notice: Our password is not returned, as we specified in our schema. Experiment with the other routes and verify that you can update and delete users as well.</p>

<p>So there you have the basics for all CRUD operations for your app. Whether you are storing Widgets, Gizmos, Comments, or Reviews, you will follow the same basic pattern. Later, when we add authentication, you'll see how we can enhance mongoose's standard methods to perform extra functionality, such as encrypting the password, before saving the user.</p>

<p>To get the code with these updates checkout commit <a href="https://github.com/bmajewski/relearning-backbone/commit/18b0d51ee45d966abf9293be9a5fe25c6af8c6a6">18b0d51ee45d966abf9293be9a5fe25c6af8c6a6</a></p>

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

<p>With a functional backend in place, we will begin to create our front end web application. We'll look at using Bower to manage dependencies and RequireJS to load modules.</p>

<p>(<strong>UPDATE</strong>: There was a bug in the PUT block of the /users/:user_id route - <em>username</em> should have been <em>email</em> - This bug was fixed in the Chapter 7 version of the code on Github and in the text above)</p>

<div class="footnotes"><ol>  
    <li class="footnote" id="fn:1">
        <p>Some people prefer to include the function in the name, such as userModel.js and userRoute.js. I go back and forth on this. They are namespaced by their directory structure, so if there is no chance I am going to get them confused, I'll shorten them like I did here. You can name them mickey, pluto, and goofy if that floats your boat. I prefer frameworks without magic naming conventions.<a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fnref:1" title="return to article"> ↩</a></p><p>
    </p></li>
    </ol></div>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 3]]></title><description><![CDATA[<p><strong>Project Structure</strong></p>

<p>We are going to start with a simple barebones structure to start with. In your project directory create both an <code>app</code> and a <code>public</code> directory. Under, <code>public</code>, create <code>assets</code>. And we're done. We'll add more as we flesh out the app. I like working iteratively, adding what we</p>]]></description><link>http://brianmajewski.com/2015/02/15/relearning-backbone-part-3/</link><guid isPermaLink="false">d22b402c-21a2-4fb1-81a8-25b81e6e0c73</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[node]]></category><category><![CDATA[npm]]></category><category><![CDATA[express]]></category><category><![CDATA[nodemon]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Sun, 15 Feb 2015 20:30:19 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/p1010298--2-.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/p1010298--2-.jpg" alt="(Re)Learning Backbone Part 3"><p><strong>Project Structure</strong></p>

<p>We are going to start with a simple barebones structure to start with. In your project directory create both an <code>app</code> and a <code>public</code> directory. Under, <code>public</code>, create <code>assets</code>. And we're done. We'll add more as we flesh out the app. I like working iteratively, adding what we need when we need it. Remember, it's <em>software</em> - we can change it if we want to.</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-11-38-14-AM.png" alt="(Re)Learning Backbone Part 3"></p>

<p><strong>NPM (Node Package Manager)</strong></p>

<p>To manage our server side dependencies, we are going to use Node's built-in package manager <a href="https://www.npmjs.com/">NPM</a>. To start, we need a <code>package.json</code> file. You can read the docs and create one by hand or you can use the tool to create one. Run  </p>

<pre><code>npm init</code></pre>

<p>in the root of your project, answer the questions, <em>et voila</em>, you should have a <code>package.json</code> file that looks something like this:</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-11-48-58-AM.png" alt="(Re)Learning Backbone Part 3"></p>

<p>If you entered something other than <code>server.js</code> for the <em>main</em> value (and you probably did, since it isn't the default), go ahead and edit the contents. <code>server.js</code> will be the main file we run to launch our web server and serve up data.</p>

<p>For our barebones server, we are going to use the following node packages: <a href="http://expressjs.com/">express</a>, <a href="https://www.npmjs.com/package/body-parser">body-parser</a>, <a href="https://www.npmjs.com/package/morgan">morgan</a>, and live</p>

<dl>  
<dt>express</dt>  
<dd>will provide nearly all of the web server functionality along with the middleware we will need to do authentication.</dd>  
<dt>body-parser</dt>  
<dd>will allow us to read json from incoming request</dd>  
<dt>morgan</dt>  
<dd>will let us log incoming requests</dd>  
</dl>

<p>Learning how to use Express would be a lesson in itself and you should dig into their documentation as needed.</p>

<p>To install these, run  </p>

<pre><code>npm install express body-parser morgan --save</code></pre>

<p>from your project root. It will download the packages, and their dependencies, and save the information to your package.json file.</p>

<p>One last package we want to download is <a href="https://www.npmjs.com/package/nodemon">nodemon</a>. When our server is running, this will watch for any changes and restart the server automatically as needed. We need to install this globally, so run:</p>

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

<p><strong>server.js</strong></p>

<p>This will be the heart of our web server.</p>

<pre><code class="language-javascript">var express = require('express');  
var bodyParser = require('body-parser');  
var morgan = require('morgan');

var path = require('path');

var app = express();

// Sets us up to read body content from POST requests
app.use(bodyParser.urlencoded({extended: true}));  
app.use(bodyParser.json());

// Adds request logging
app.use(morgan('dev'));

// Sets up the server to serve static files from the public directory
app.use(express.static(__dirname + '/public'));

// For all requests we do not explicitly handle (*), return index.html
app.get('*', function(req,res){  
    res.sendFile(path.join(__dirname + '/public/index.html'));
});


// Listen on port 1337
var port = 1337;  
app.listen(port);  
console.log('Server up and running on port ' + port);  
</code></pre>

<p>So, what's going on here? </p>

<ul>
<li>First we define our dependencies and create an <code>app</code> variable to represent the application/server.</li>
<li>Then, we use the <em>body-parser</em> package to tell our app how to get JSON from the body of incoming requests. </li>
<li>We activate <em>morgan</em> in dev mode, which will log our requests.</li>
<li>We define a directory to serve up static resources like html, css, fonts, etc. <code>__dirname</code> is provided by the <em>path</em> package.</li>
<li>Finally, for all incoming requests that have not been handled yet(<code>*</code>), we return <code>index.html</code>. So, if we ask for a specific CSS file, the static instruction above will handle it. If we ask for an HTML page that doesn't exist, this instruction will handle it. We will be adding more routes and instructions as we go on. As you can see, the order in which we define these routes is important. Express will go through each one until it comes to a handler that satisifes the request. This is a classic implementation of the <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility</a> pattern.</li>
</ul>

<p>That's it. That's all you need to have a basic web server. We could have left out the body-parser section for an even leaner file, but we will need it next. Run  </p>

<pre><code>nodemon server.js</code></pre>

<p>and you should see output similar to: <br>
<img src="http://brianmajewski.com/content/images/2015/02/Screen-Shot-2015-02-15-at-12-19-18-PM.png" alt="(Re)Learning Backbone Part 3"></p>

<p>We can create a simple <code>index.html</code> file in our public directory and view it in a browser. To ensure that static files are being served up as well, create a <code>css</code> folder under <code>assets</code> and add a <code>styles.css</code> file.</p>

<p><em>Sample HTML</em>  </p>

<pre><code class="language-markup">&lt;!DOCTYPE html&gt;  
&lt;html&gt;  
&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;/head&gt;  
&lt;body&gt;  
&lt;h3&gt;Relearning Backbone&lt;/h3&gt;  
&lt;/body&gt;  
&lt;/html&gt;  
</code></pre>

<p><em>Sample CSS</em>  </p>

<pre><code class="language-css">h3 {  
    color: #4169e1;
}
</code></pre>

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

<p>Next time, we are going to add a database connection to the server, and some User entities to it.</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 2]]></title><description><![CDATA[<blockquote>
  <p>Opinions are like birthdays: everyone has one and I heard about yours on Facebook.</p>
</blockquote>

<p><strong>Tool Sets and Libraries</strong></p>

<p>This is easily the most opinionated part of this process. I am always open to code changes; hearing the viewpoints of other developers who may have more experience or a different perspective</p>]]></description><link>http://brianmajewski.com/2015/02/13/relearning-backbone-part-2/</link><guid isPermaLink="false">7625c66a-c76c-42cd-9b86-2f382fbdbb44</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[intellij]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[node]]></category><category><![CDATA[brew]]></category><category><![CDATA[mac]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 13 Feb 2015 16:36:57 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/construction408661.jpg" medium="image"/><content:encoded><![CDATA[<blockquote>
  <img src="http://brianmajewski.com/content/images/2015/02/construction408661.jpg" alt="(Re)Learning Backbone Part 2"><p>Opinions are like birthdays: everyone has one and I heard about yours on Facebook.</p>
</blockquote>

<p><strong>Tool Sets and Libraries</strong></p>

<p>This is easily the most opinionated part of this process. I am always open to code changes; hearing the viewpoints of other developers who may have more experience or a different perspective often lead me to change my code. We call it <em>software</em> for a reason. It should be malleable. It should adapt. When it comes to my tools, however, that's a different story.</p>

<p><strong>OS - Mac OS X</strong></p>

<p>Let's get the holy war out of the way. If you use Windows, more power to you. You must like the extra challenges of playing on <em>Expert</em> mode. For me, there are three key reasons I develop on the Mac.</p>

<dl>  
<dt>Environment</dt>  
<dd>Most every environment I am going to deploy to is a *nix variant. Having a BASH (or similar) shell integrated into the OS allows me to create workflows that work everywhere I do.</dd>  
<dt>The Cool Kids Use It</dt>  
<dd>Most of the developers and designers that I read and learn from are using it. This isn't simply a case of "me too!" This is a case where I want zero impediments in my way of completing my task. If they recommend a tool or a library or even some non-web-dev related utility, I'd rather be able to copy them than go searching for an equivalent.</dd>  
<dt>Comfort</dt>  
<dd>I've worked on Apple hardware since the Apple][ days. It just makes more sense to me.</dd>  
</dl>

<p>So, yeah, use Windows if you want. Good luck with that.</p>

<p><strong>IDE - Jetbrains IntelliJ IDEA (or Webstorm)</strong></p>

<p>I'm maybe a little bit more flexible on this issue, but not by much. As a professional developer who works with a number of different languages and technologies, having a tool that works across all of them is something I find is worth my investment in time and money. I've been using it since Version 1 when I met the original developers at a conference in Prague. It has been my <a href="https://www.jetbrains.com/idea/">IDE of choice</a> ever since. Any good text editor like <a href="http://www.sublimetext.com/">Sublime</a> or <a href="https://atom.io/">Atom</a> can be a useful tool with the right setup and plugins. IDEA mostly works out of the box with deep support for things like Node, Angular, Grunt, and the like.</p>

<p><strong>Brew</strong></p>

<p><a href="http://brew.sh/">Brew</a> is "The missing package manager for OS X" and allows you to install and maintain the tools used to develop and build. Get it. Install it. If you like GUIs, get <a href="https://www.cakebrew.com/">Cakebrew</a>.</p>

<p><strong>Node</strong></p>

<p>We're going to use <a href="http://nodejs.org/">Node</a> to stand up a web server to serve our REST endpoints and access the database. <strong>DO NOT</strong> simply go to the website, download the package and install it. You'll end up in a world of hurt, having to run everything as <em>sudo</em>. Use Brew (see above). <code>$ brew install node</code>  Should we switch over to <a href="https://iojs.org/en/index.html">io.js</a>? Maybe? This is one of those rat holes I wanted to avoid with this project. Investigating io.js is an endeavor for another day.</p>

<p><strong>MongoDB</strong></p>

<p>Is <a href="http://www.mongodb.org/">MongoDB</a> the right database for your application? Who knows? For this project, we want a simple document datastore that has some easy integration with javascript. We could serve up JSON files instead of hitting a datastore, but that doesn't meet the requirements of having a fully functional application from soup to nuts to build off. We can always swap it out for another technology. Again, use Brew to install it.</p>

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

<p>At this point, we have the makings for a web server that can serve up data. Well, we have the tools anyways. In the next installment, we'll create a project structure and web server we'll use throughout the project.</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 1]]></title><description><![CDATA[<p><strong>A Little Bit of History</strong></p>

<p>Two years ago, I was dropped head first into a large corporate Javascript project. Our flagship application's front end at the time was being developed in GWT. It had become too large for its own  good: long compile times, a complicated Gradle build process orphaned</p>]]></description><link>http://brianmajewski.com/2015/02/09/relearning-backbone-part-1/</link><guid isPermaLink="false">9df03847-c1bd-475f-8a07-6ccbb0b41ab0</guid><category><![CDATA[development]]></category><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Mon, 09 Feb 2015 16:40:53 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/Snake_backbone_4.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/Snake_backbone_4.jpg" alt="(Re)Learning Backbone Part 1"><p><strong>A Little Bit of History</strong></p>

<p>Two years ago, I was dropped head first into a large corporate Javascript project. Our flagship application's front end at the time was being developed in GWT. It had become too large for its own  good: long compile times, a complicated Gradle build process orphaned by a developer who had moved on to a new job, and, most importantly, the difficulty of incorporating new open source Javascript frameworks for things like graphing or animations.</p>

<p>My boss, the VP of Engineering, felt our pain and championed the decision to "forklift" our app over to a pure Javascript implementation. In hindsight, this was probably a too ambitious task given a team of Java developers with minimal and/or rusty Javascript skills. The project was a go, however, and we moved forward.</p>

<p>We spent a good amount of time up front reviewing our options. At the time, Ember and Angular held a lot of promise, but ultimately were too green for our project. We wanted to engage with an outside firm to help kickstart the project and develop some patterns for our team to learn from. We needed to pick something that would assist us in making the language switch without being overly prescriptive.</p>

<p><strong>Enter Backbone</strong></p>

<p>For the first 6 weeks or so, our team of two external consultants took our existing application and created a new framework, based on Backbone. The goal was for a minimally functional application, working end to end - authentication, consuming (existing) REST services, displaying data and persisting changes. A basic CRUD application that our internal team could iterate on. </p>

<p>Of course, our "partners" in Marketing insisted that there be no UX changes, no functional changes, and that it be updated with a new CSS makeover. Additionally, any internal application SMEs had long ago left the company, so any information regarding how a feature worked, why something might be validated in a certain way, etc. was to be gleaned from the existing codebase, written primarily by developers long since gone. Oh, it had to be done in 6 months, and this would be blocking any new feature development and potentially impacting our deliverables.</p>

<p>My team rose to the occasion. Given all of these constraints, they developed a good-looking, performant application that was identically functional in an amazing timeframe. The pace of this development did come at a cost: There was no time for reflection, refinement, or absorption. Development challenges would arise, square pegs were jammed in round holes, and we moved on to the next feature. Aha moments were never shared. But we delivered.</p>

<p><strong>And Now?</strong></p>

<p>In the time since then, I have taken on professional engagements with both Angular and Ember projects. There have been so many times when I have been able to quickly do something that frustrated me for days previously. This, however, is due to simply being more proficient and comfortable in the development space. Both of these frameworks introduce their own flavors of complexity and challenges.</p>

<p>Currently my team maintains and enhances a large, but relatively straightforward, Ember application. Even so, I hear complaints about not 'getting the framework' and developers feel they are 'poking around and making tweaks', having not really had the immersive indoctrination to Ember.</p>

<p>Personally, I have a number of side projects that I would like to work on. My biggest stumbling block is picking a technology stack to start with and actually working on the project part. I find I'll read about a new framework, spend some time dinking through the tutorials, have some minimal Todo MVC clone, and then be left where I started. So I set myself out a challenge.</p>

<p><strong>The Challenge</strong></p>

<p>Instead of working on a project for the feature set, I would work on building out a scaffold that I could then use as a starting point for a project. The scaffold had to be more than some directory structures. It had to be what I asked that consulting firm for a few years ago: A working end to end application with authentication, REST interaction, etc. Something I could start adding features to from the jump.</p>

<p>Recently, <a href="http://derickbailey.com/email_archive/yes-your-code-is-opinionated/">Derick Bailey</a> wrote about "opinionated frameworks". This made me think that, even more so than the frameworks, my code is opinionated. I want it to work in a way that makes sense to <em>me</em>. Libraries and frameworks are great at speeding up development, but in many cases they abstract away the details too much, and obscure a fundamental understanding of what they are doing, and more importantly, <em>why</em>. I picked Backbone as my base and dug in.</p>

<p>This past weekend, from scratch, I built up the first iteration of the project. I did in about 20 hours what I formerly paid a couple guys to do in 6 weeks. More importantly, I understand every single line of code and why I put it there. Is it perfect? Hell no. Could it be improved? Of course, and it will be. What it is is tangible. I can fork the repo today and start building out a new app. Which, hopefully, now I will do.</p>

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

<p>Over the next few weeks, I will break down the app into chunks and talk about how it works and why it works. If you follow along, hopefully, you too will understand a little bit more about how a single page application works end to end. Whether you stay with Backbone or choose a more inclusive framework, I hope that you'll learn a bit more than following along with code samples from a contrived example.</p>

<p>Next Time: Tool Sets and Libraries</p>]]></content:encoded></item></channel></rss>