2011-12-28 26 views
6

如何知道渲染函数中视图模型的哪个属性发生了更改? (在渲染函数中,“e”是模型,但我只需要改变的属性)。我需要知道这一点以知道使用哪个模板。还是有另一种方法来做到这一点?backbone.js查看确定模型的哪个属性发生了变化

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; 
    } 
}); 
+0

下面提供的解决方案两个答案,但最简单的一个正在使用一个更具体的事件,如更改:您的案例中的attrName更改:名称... – Sander 2011-12-28 22:07:24

回答

14

我相信changedAttributes功能是你在找什么

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

,或者检查是否有特定的属性已经改变使用功能hasChanged

hasChangedmodel.hasChanged([属性])
具有典型的自上次 “改变” 事件改变了吗?如果传递了一个属性,如果该特定属性已更改,则返回true 。

var nameChanged = this.model.hasChanged("name"); 
相关问题