Backbone stickit - bind using class names and qualified "this"

531 views Asked by At

I often find myself providing some sort of naming convention for stickit jQuery target IDs, in the form some-aggregate-individual-element-{#number} pairing each ID with a corresponding collection element in a one-to-one fashion. This is to ensure that stickit will update only the particular View in question and not other similar aggregate views.

It seems like there should be a way to use, say, class names rather than IDs for this purpose if you could somehow tell stickit the "root" node to perform updates under. For instance, if I am defining a View and I say bindings: { ".individual-title": { observe: "Title" } }, stickit knows that the Title attribute is coming from this.model so there is no need for qualification. However, whenever I apply the same logic to the left hand side, stickit performs updates against ALL nodes on the document with that class name rather than only those nodes that live under this.$el, where $el is the root node of my view.

Is there a built-in or otherwise easy way to achieve this so I can stop iding all of my elements with silly naming conventions? Or is this what you are supposed to be doing?

1

There are 1 answers

2
TYRONEMICHAEL On

I actually bind to the name attribute on on the form element, therefore eliminating the use of ids and classnames. So for example lets say I have the following model.

User.Model = Backbone.Model.extend({
    defaults: {
        firstname: null,
        lastname: null,
        phone: null,
        personemail: null
    }
});

I then create the following helpers:

// Create default binding therefore eliminating repetition
Backbone.View.prototype.createDefaultBindings = function() {
    var k, v, _ref, _results;
    this._bindings = {};
    _ref = this.model.toJSON();
    _results = [];
    for (k in _ref) {
        v = _ref[k];
        _results.push(this._bindings['input[name="' + k +'"]'] = { observe: k });
    }
    return _results;
};

// Helper to overide bindings in our view
Backbone.View.prototype.mergeBindings = function() {
    if (this.model) {
        this.createDefaultBindings();
    }
    _.extend(this._bindings, this.bindings);
    this.bindings = this._bindings;
};

Then we can have the following view:

User.Views.Form = Backbone.View.extend({
    initialize: function(options) {
        this.mergeBindings();
    },

    render: function() {
        this.stickit();
    }
});

Initialize our view

var view = new User.Views.Form({ model: new User.Model() })

It would then bind to your template with the the following inputs:

<input name="firstname" type="text">
<input name="lastname" type="text">
<input name="phone" type="text">
<input name="email" type="text">