backbone.js View determine which attribute of model is change

Florim Maxhuni picture Florim Maxhuni · Dec 28, 2011 · Viewed 11.6k times · Source

How can I know which attribute of the view model is changed in the render function? (In the render function, "e" is the model, but I need only the attribute which is changed.) I need to know this to know which template to use. Or is there another method to do this?

window.Person = Backbone.Model.extend({});

window.Njerzit = Backbone.Collection.extend({
    model: Person,
    url: '/Home/Njerzit'
});

window.PersonView = Backbone.View.extend({
    tagName: 'span',

    initialize: function () {
        _.bindAll(this, 'render');
        this.model.bind('change', this.render);
    },

    render: function (e) {
        //if model name is changed, I need to render another template
        this.template = _.template($('#PersonTemplate').html());
        var renderContent = this.template(this.model.toJSON());
        $(this.el).html(renderContent);
        return this;
    }
});

Answer

soldier.moth picture soldier.moth · Dec 28, 2011

I believe the changedAttributes function is what you're looking for

changedAttributesmodel.changedAttributes([attributes])
Retrieve a hash of only the model's attributes that have changed. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.

or to check if a specific attribute has changed use the hasChanged function

hasChangedmodel.hasChanged([attribute])
Has the model changed since the last "change" event? If an attribute is passed, returns true if that specific attribute has changed.

var nameChanged = this.model.hasChanged("name");