How to Clone Models in Backbone

拈花ヽ惹草 提交于 2019-12-03 14:54:53

问题


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).


回答1:


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



回答2:


You can give Backbone.Memento a try.

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.




回答3:


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


来源:https://stackoverflow.com/questions/17517028/how-to-clone-models-in-backbone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!