Skip to content Skip to sidebar Skip to footer

How To Clone Models In Backbone

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

Solution 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 referencesthis._modelAttributes = _.extend({}, this.model.attributes);
    },
    onSave: function() {
        // revert to initial state.this.model.set(this._modelAttributes);
    }
});

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

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

varModel = Backbone.Model.extend({
    'title': 'Hello'
});

varView = Backbone.View.extend({
    initialize: function() {

        // Holds temporary values until savethis.cache = {};

    },
    onTitle: function() {
        this.cache.title = 'World';
    },
    onSave: function() {
       this.model.set( this.cache );
    }
});

Post a Comment for "How To Clone Models In Backbone"