rampr
rampr

Reputation: 1947

Previous attribute of backbone.js isn't persistent

I'm trying to use the example mentioned for using the previous api in Backbone's Model. I've pasted the example below

var bill = new Backbone.Model({
  name: "Bill Smith"
});

bill.bind("change:name", function(model, name) {
  alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

The previous value in the alert is Bill Smith which is correct. But if I try to access this in firebug by calling

bill.previous("name");

it is Bill Jones and not Bill Smith. Why is it so? What am I missing ?

Upvotes: 5

Views: 8296

Answers (1)

Paul
Paul

Reputation: 2157

Well, if you look at Backbone's source, you'll see that the _previousAttributes attribute in Backbone.Model is reset to a copy of the current attributes after the 'change' events have been fired (in the change method: this._previousAttributes = _.clone(this.attributes);).

I think I've seen issues on Github about this behavior before; it's unexpected to a lot of people.

Edit: found it; a quote from the author in https://github.com/documentcloud/backbone/pull/373 :

I'm afraid that the current behavior is how things are supposed to work. Previous attributes are only available during the course of a "change" event. Without this, the entire notion of hasChanged() makes no sense.

If you're looking for more robust undo-like functionality, I'd recommend keeping a true list of previous versions of the model.

Upvotes: 13

Related Questions