我正在用 Backbone.js 构建一个应用程序。我的一些服务器端 API 将返回自特定时间以来所有新的或更改的模型。其中一些对象可能是我收藏的新对象,因此我可以添加它们。其他人可能已经存在,在这种情况下,我想更新现有模型。所以基本上我正在寻找upsert(更新或插入)功能。
这类似于在 0.9.0 中添加的 {add:true} 选项,只是我也想更新。
有没有一种简单/已知的方法来做到这一点?更新代码似乎并不难,但我不想重新发明轮子。
最佳答案
我已经用通用方法解决了这种情况:
App.Utils = {
refreshCollection: function( collection, collectionJSON ){
// update/add
_( collectionJSON ).each( function( modelJSON ) {
var model = collection.get( modelJSON.id );
if( model ) {
model.set( modelJSON );
} else {
collection.add( modelJSON );
}
});
// remove
var model_ids_to_keep = _( collectionJSON ).pluck( "id" );
var model_ids = collection.pluck( "id" );
var model_ids_to_remove = _( model_ids ).difference( model_ids_to_keep )
_( model_ids_to_remove ).each( function( model_id_to_remove ){
collection.remove( model_id_to_remove );
});
},
}
参数
collection
: 是一个 Backbone.Collection collectionJSON
: 是一个带有 Hash 样式的模型数据的数组。典型的 JSON 响应。 我相信它可以优化,尤其是删除部分。但我保持这样的可读性,因为我仍在进行测试。
使用示例
// code simplified and no tested
var VolatileCollection = Backbone.Collection.extend({
// url:
// model:
// so on ...
})
var PersistentCollection = Backbone.Collection.extend({
// url: not needed due this Collection is never synchronized or changed by its own
// change the VolatileCollection instead, all changes will be mirrored to this Collection
// through events
// model: the same
initialize: function( opts ){
this.volatileCollection = opts.volatileCollection;
this.volatileCollection.on( "reset", this.update, this );
this.volatileCollection.on( "change", this.update, this );
}
update: function(){
App.Utils.refreshCollection( this, this.volatileCollection.toJSON() );
}
})
var volatileCollection = new VolatileCollection();
var persistentCollection = new PersistentCollection({ volatileCollection: volatileCollection });
volatileCollection.fetch();
关于Backbone.js 集合更新插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9640095/