Skip to content

Instantly share code, notes, and snippets.

@brenopolanski
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brenopolanski/6f646a35916af14cdeb5 to your computer and use it in GitHub Desktop.
Save brenopolanski/6f646a35916af14cdeb5 to your computer and use it in GitHub Desktop.
How to Clone Models in Backbone

via: stackoverflow

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);
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment