6

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;
    }
});
Thaddeus Albers
  • 4,094
  • 5
  • 32
  • 42
Florim Maxhuni
  • 1,421
  • 1
  • 17
  • 35
  • both answers below offer solutions, but the easiest one is using a more specific event like the change:attrName in your case change:Name ... – Sander Dec 28 '11 at 22:07

2 Answers2

14

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");
Bobby
  • 18,217
  • 15
  • 74
  • 89
12

You can bind to change:name if you only want to notify if the name has changed: http://documentcloud.github.com/backbone/#Model-set

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297