6

我如何知道渲染函数中视图模型的哪个属性发生了变化?(在渲染函数中,“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;
    }
});
4

2 回答 2

14

我相信该changedAttributes功能是您正在寻找的

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

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

hasChangedmodel.hasChanged([attribute])
自上次“更改”事件以来,模型是否发生了变化?如果传递了一个属性,则如果该特定属性已更改,则返回 true。

var nameChanged = this.model.hasChanged("name");
于 2011-12-28T21:46:57.667 回答
12

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

于 2011-12-28T21:59:23.353 回答