Backbone Bindings

Bind element properties to Backbone model attributes with optional transformations, inspired by Cocoa bindings.


When working with Backbone it is common to re-render a whole view when a model attribute has changed. We can do better than that. Inspired by bindings in Cocoa (iOS & Mac) applications, I’ve created a library that allows you to bind element properties to model attributes, with optional transformation in between. I wanted bindings to be as simple as Backbone.View.events.

var categoryClassTransformer = function(value) {
    return (value) ? value.toLowerCase().replace(/ /g, '') : '';
};

var triedClassTransformer = function(value) {
    return (value == true) ? 'tried' : 'todo';
};

var Meal = Backbone.Model.extend({});

var MealLogView = Backbone.View.extend({
    tagName: 'form',
    className: 'meal-log',
    template: _.template($('#meal-log').html()),
    bindings: {
        'class': ['category', categoryClassTransformer],
        'class': ['tried', triedClassTransformer],
        'text h1.name': 'name',
        'value input[name="name"]': 'name',
        'value textarea[name="notes"]': 'notes',
        'checked input[name="tried"]': 'tried'
    },
    events: {
        'submit': 'save'
    },
    save: function(event) {
        alert("Save: " + JSON.stringify(this.model.toJSON()));
        return false;
    },
    render: function() {
        this.$el.html(this.template());
        return this.bindModel();
    }
});

See it in action on JSFiddle.

GitHub stars

← All posts