我有一个相当通用的模型和该模型的集合(见下文)我正在处理作为一系列视图的基础.在几个视图中,其中一个模型的选择会生成动作(通过'selected'属性),我需要能够在客户端跟踪选择.
但是,似乎在Backbone中没有干净的方法可以做到这一点.在客户端上模型上添加/更改的任何属性都将同步到服务器.{silent : yes}更改该属性时我无法使用,因为当change事件触发该属性时,我需要触发视图中的更改.我想出这个的唯一方法是覆盖save函数Backbone.Model
我的问题:有没有办法让我缺少客户端唯一的属性,或者我的方法在结构方面存在缺陷,我只是没有看到?
var CSEvent = Backbone.Model.extend({
idAttribute: "_id",
urlRoot : '/api/events',
defaults: {
title : "",
type : "Native",
repeatOrOneTime : "OneTime",
selected : false
}
});
var CSEventCollection = Backbone.Collection.extend({
model: CSEvent,
url: '/api/events',
getSelectedEvent : function() {
return this.find(function(csevent) { return csevent.get('selected') === true; });
},
selectEvent : function(eventId) {
this.deselectEvent();
this.get(eventId).set({selected : true});
},
deselectEvent : function() {
this.getSelectedEvent().set({selected : false});
}
});
Run Code Online (Sandbox Code Playgroud)
尝试覆盖该Model.toJSON()方法,正如您在Backbone Model代码中看到的,这种方法并不是很复杂.官方文档也建议在有特殊需要的情况下覆盖它.
尝试这样的事情:
var CSEvent = Backbone.Model.extend({
toJSON: function(){
return _.clone( _.pick( this.attributes, "title", "type", "repeatOrOneTime" ) );
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1917 次 |
| 最近记录: |