如何克隆骨干模型 [英] How to Clone Models in Backbone

查看:120
本文介绍了如何克隆骨干模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有可以按一​​定的视图编辑的模型;然而,在视图的底部,用户应该得到一个选项来保存或放弃所有更改。这意味着你将需要存储到模型中所做的所有更改的列表,然后进行一次保存按钮被点击这些变化。这听起来过于复杂,我想出了一个替代方法的想法是创建模型的克隆,并在视图改变了这一点。然后,如果用户点击保存删除旧的模式,其收藏用新的替换它,否则你放弃克隆模式。

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?

这是等同于从服务器获取一次数据(但一个额外的HTTP请求,似乎没有必要)。

This would be equivalent to fetching the data from the server again (but an extra HTTP request seems unnecessary).

推荐答案

您可以使用 克隆 方法。下面简单的例子:

You could use the clone method. Short example below:

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

这篇关于如何克隆骨干模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆