javascript 如何在 Backbone 中克隆模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17517028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Clone Models in Backbone
提问by Joshua Bambrick
I have a model which can be edited by a certain view; however, at the bottom of the view the user should get an option to save or discard all changes. This means that you will need to store a list of all the changes to be made to the model and then make those changes only once the 'save' button has been clicked. This sounds unnecessarily complicated and I have come up with an idea of an alternative approach which is to create a clone of the model and make changes to that in the view. Then if the user clicks 'save' delete the old model and replace it in its collection with the new one, otherwise you discard the cloned model.
我有一个模型,可以通过某个视图进行编辑;但是,在视图底部,用户应该可以选择保存或放弃所有更改。这意味着您需要存储要对模型进行的所有更改的列表,然后仅在单击“保存”按钮后才进行这些更改。这听起来不必要地复杂,我想出了一个替代方法的想法,即创建模型的克隆并在视图中对其进行更改。然后,如果用户单击“保存”,则删除旧模型并将其在其集合中替换为新模型,否则您将丢弃克隆模型。
This this an acceptable approach, and if so, how can I implement the cloning process?
这是一种可接受的方法,如果是这样,我该如何实施克隆过程?
This would be equivalent to fetching the data from the server again (but an extra HTTP request seems unnecessary).
这相当于再次从服务器获取数据(但额外的 HTTP 请求似乎没有必要)。
回答by kalley
You could use the clone
method. Short example below:
你可以用这个clone
方法。下面的简短示例:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
this.realModel = this.model;
this.model = this.realModel.clone();
},
onSave: function() {
this.realModel.set(this.model.attributes);
}
});
You could also do something a bit different:
你也可以做一些不同的事情:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
// save the attributes up front, removing references
this._modelAttributes = _.extend({}, this.model.attributes);
},
onSave: function() {
// revert to initial state.
this.model.set(this._modelAttributes);
}
});
回答by Rifat
You can give Backbone.Mementoa try.
你可以试试Backbone.Memento。
If you don't want to use it no problem. But, You can get a good idea about how it should be done from the codebase.
如果你不想使用它没有问题。但是,您可以从代码库中很好地了解它应该如何完成。
回答by shrunyan
I usually solve this issue with an object cache on the view. That way I don't add any unnecessary overhead to model/view management. Discarding happens naturally if the user closes out of a view without saving.
我通常使用视图上的对象缓存来解决这个问题。这样我就不会为模型/视图管理增加任何不必要的开销。如果用户在没有保存的情况下关闭视图,则丢弃自然会发生。
var Model = Backbone.Model.extend({
'title': 'Hello'
});
var View = Backbone.View.extend({
initialize: function() {
// Holds temporary values until save
this.cache = {};
},
onTitle: function() {
this.cache.title = 'World';
},
onSave: function() {
this.model.set( this.cache );
}
});