View确定模型的哪个属性被更改了

backbone.js View determine which attribute of model is change

本文关键字:属性 模型 View      更新时间:2023-09-26

我如何知道视图模型的哪个属性在渲染函数中被更改?(在渲染函数中,"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;
    }
});

我相信changedAttributes函数是您正在寻找的

changedAttributesmodel.changedAttributes([属性])
仅检索已更改的模型属性的散列。可选地,可以传入外部属性散列,返回属性在这个散列中,它与模型不同。这可以用来计算指出视图的哪些部分应该更新,或者哪些调用需要更新将更改同步到服务器。

或使用hasChanged函数检查特定属性是否已更改

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

var nameChanged = this.model.hasChanged("name");
  • From Backbone Docs

你可以绑定到change:name如果你只想通知如果名称已经改变:http://documentcloud.github.com/backbone/#Model-set