Search code examples
backbone.jsbackbone-stickit

backbone.js nested object attribute with stickit.js


I am using stickit.js to achieve two way data binding. I am please to know how do I bind stickit with nested object attribute. For an E.g.

var Person = Backbone.Model.extend({
    defaults:{
        name: {
            first: 'James',
            last: 'White'
        }
    }
});

I wonder it is possible to bind a text input some thing like this.

<input type="text" name="firstname" class="first-name"/>


bindings: {
    '.first-name': 'name.first'
}

Solution

  • Sounds like you could use a feature called computeds.

    Computeds are binding fields that are calculated on the fly and may be compounds of other model fields.

    I can't see this kind of feature in the stickit docs, though. So you could give the really excellent model-binding library backbone-epoxy a shot. I made a jsfiddle for you.

    var Person = Backbone.Epoxy.Model.extend({
        defaults:{
            name: {
                first: 'James',
                last: 'White'
            }
        },
        computeds: {
            fullname: function() {
                return this.get('name').first + ' ' + this.get('name').last;
            }
        }
    });
    
    var view = new Backbone.Epoxy.View({
        el: '#app',
        model: new Person()
    });
    

    And the html:

    <div id="app">
        <input type="text" data-bind="value:fullname" />
    </div>