backbone.js View确定模型的哪个属性发生了变化

Flo*_*uni 6 javascript backbone.js backbone-model

如何知道在渲染函数中更改视图模型的哪个属性?(在渲染函数中,"e"是模型,但我只需要更改的属性.)我需要知道这个以了解要使用的模板.或者还有另一种方法吗?

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

sol*_*oth 14

我相信这个changedAttributes功能正是你要找的

changedAttributesmodel.changedAttributes([attributes])
仅检索已更改的模型属性的哈希值.(可选)可以传入外部属性哈希,返回该哈希中与模型不同的属性.这可用于确定应更新视图的哪些部分,或者需要进行哪些调用以将更改同步到服务器.

或检查特定属性是否已更改使用该hasChanged功能

hasChangedmodel.hasChanged([attribute])
自上次"更改"事件以来模型是否已更改?如果传递了属性,则在特定属性发生更改时返回true.

var nameChanged = this.model.hasChanged("name");
Run Code Online (Sandbox Code Playgroud)


And*_*rle 12

change:name如果您只想通知名称是否已更改,则可以绑定:http://documentcloud.github.com/backbone/#Model-set