Backbone.js Data Binding

In the client-side application development world there are many different choices for development but it seems that at the time of this writing in late 2013 there is a lot of focus on “the big 3”: Backbone.js AngularJS and Ember.js One of the elements that people like a lot about AngularJS and Ember.js (or even something like Knockout.js) is that you get data binding capability out of the box where when something in the view changes, the appropriate model is updated accordingly. So if a user is typing something into an input field, the model value is being set as he or she types. This is something that Backbone.js does not really have natively… yet (as of October 2013).

Certainly, if you wanted to you could load up one of the many libraries that implement data binding in Backbone.js in some manner or another. However, as it turns it’s not really too difficult to integrate this functionality into what you are likely already doing with Backbone.js, so loading up a whole different library is probably unnecessary in most cases. In what follows, we’re going to look at how you can hook up your Backbone models to respond to changes in the view as they occur.

To start we’ll create our single-page application. We’ll add a template that will be used by the view…

<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/underscore.js" type="text/javascript"></script>
<script src="js/backbone.js" type="text/javascript"></script>
</head>
<body>

<div class="list"></div>

<script type="text/template" id="artistTemplate">
    Enter Artist Name:<input class="nameField" />
    <p>The name you entered is <span class="nameText"></span></p>
</script>

</body>
</html>

Next let’s add our view along with the code to to render our view to the <div> container…

<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/underscore.js" type="text/javascript"></script>
<script src="js/backbone.js" type="text/javascript"></script>
</head>
<body>

<div class="list"></div>

<script type="text/template" id="artistTemplate">
    Enter Artist Name:<input class="nameField" />
    <p>The name you entered is <span class="nameText"></span></p>
</script>

var ArtistList = Backbone.View.extend({
    el: '.list',

    initialize: function() {
    },

    render: function() {
        var markup = _.template($('#artistTemplate').html());
        this.$el.html(markup);
    }
});
var artistList = new ArtistList();
artistList.render();

</body>
</html>

At this point we’ll be able to see our template with the input field and paragraph on the page.

Now let’s work on the model. The model we’ll be using is below…

 var Artist = Backbone.Model.extend({

    defaults:{
        name: 'New Artist',
        birthday: 'January 1, 1970',
        hometown: 'Los Angeles, CA',
        favoriteColor: 'blue',
    },

    initialize: function() {
        console.log('New artist created...');
    }

});

We don’t need to worry about handling any change events in our model because we’ll be working with an instance of the model in the view. To do this, we’ll initialize our model in the view…

var ArtistList = Backbone.View.extend({
    el: '.list',

    initialize: function() {
        this.artist = new Artist({ name: '2Pac', birthday: 'June 16, 1971', hometown: 'Harlem, New York, NY', favoriteColor: 'blue'});
    },

    ...
});

Now the fun part: data binding. In our example we’re going to update the model (artist) attached to the view as the user types into the input field. Do do this we’re going to attach a callback function to the “keyup” event. If you wanted to you could attach a callback to the “change” event. However, in that case the model would not actually change until the user removes focus from the input field. So let’s attach our event to the view…

var ArtistList = Backbone.View.extend({
    el: '.list',

    initialize: function() {
        this.artist = new Artist({ name: '2Pac', birthday: 'June 16, 1971', hometown: 'Harlem, New York, NY', favoriteColor: 'blue'});
    },

    render: function() {
        var markup = _.template($('#artistTemplate').html());
        this.$el.html(markup);
    },
    events: {
        "keyup .nameField" : "nameChanged",
    }
});

So we’re going to need to add our “nameChanged” callback function…

var ArtistList = Backbone.View.extend({
    el: '.list',

    initialize: function() {
        this.artist = new Artist({ name: '2Pac', birthday: 'June 16, 1971', hometown: 'Harlem, New York, NY', favoriteColor: 'blue'});
    },

    render: function() {
        var markup = _.template($('#artistTemplate').html());
        this.$el.html(markup);
    },
    events: {
        "keyup .nameField" : "nameChanged",
    },

    nameChanged: function(){
        console.log('Artist model changed...');
        var newName = $('.nameField').val();
        this.artist.set('name', newName);
        $('.nameText').html(newName);
    }

});

Now, as we type into the input field the “artist” model is updated. We have “data bound” our input field to our model. We can see the text logging to the console as we type. Great success! You could also console.log(this.artist) to see the actual values being updated on the model.

Now, this could potentially be a challenge from a scaling perspective as the number of models that you have increases because you’ll have to link all of these up in the views… but this could probably be abstracted into a separate method that you can call by passing in the different objects that you’re working with. See this article on Extending Backbone.js for some potential ways to add methods to your models, views, or both. In the end, you’re probably in pretty good shape regardless of what path you choose to take. This demo shows that it’s really not a complicated process to implement data binding in Backbone.js directly into your application without the overhead of loading up yet another library.

The demo for this application is below…

View Demo Download Files

Until next time, happy data binding.

, , 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Backbone.js Data Binding

    Leave a Reply

    Your email address will not be published. Required fields are marked *