Skip to content

Commit

Permalink
implementing clear, fixing variable scoping
Browse files Browse the repository at this point in the history
  • Loading branch information
jondot committed Aug 30, 2011
1 parent ef83574 commit 4537b9f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 11 deletions.
34 changes: 23 additions & 11 deletions backbone.memento.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,25 @@ Backbone.Memento = (function(model){

function removeAttributes(model, attrsToRemove){
for (var index in attrsToRemove){
attr = removedAttrs[index];
attr = attrsToRemove[index];
model.unset(attr);
}
}

function restoreState(last){
//get the previous state
var attrs = attributeStack[last];

//handle removing attributes that were added
var removedAttrs = getRemovedAttrDiff(attrs, model.toJSON());
removeAttributes(model, removedAttrs);

//restore the previous state
model.set(attrs);

//destroy the no-longer-current state
delete attributeStack[last];
}

return {
version: "0.1.1",
Expand All @@ -45,18 +60,15 @@ Backbone.Memento = (function(model){
if (last < 0)
return null;

//get the previous state
attrs = attributeStack[last];

//handle removing attributes that were added
removedAttrs = getRemovedAttrDiff(attrs, model.toJSON());
removeAttributes(model, removedAttrs);
restoreState(last);
},

//restore the previous state
model.set(attrs);
clear: function(){
if(attributeStack.length === 0){
return null;
}

//destroy the no-longer-current state
delete attributeStack[last];
restoreState(0);
}
}
});
35 changes: 35 additions & 0 deletions spec/javascripts/memento.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,39 @@ describe("memento", function(){
expect(changed).toBeTruthy();
});
});

describe("when clearing", function(){
it("should restore to first memento given successive save points", function(){
var changed = false;
this.model.set({foo: "bar"});
this.model.store();
this.model.set({foo: "baz"});
this.model.store();
this.model.set({foo: "qux"});
this.model.store();

this.model.bind("change:foo", function(){
changed = true;
});

expect(this.model.get('foo')).toBe('qux');
this.model.clear();
expect(changed).toBeTruthy();
expect(this.model.get('foo')).toBe('bar');
});


it("should do nothing given no store point", function(){
var changed = false;
this.model.set({foo: "bar"});

this.model.bind("change:foo", function(){
changed = true;
});
this.model.clear();

expect(this.model.get('foo')).toBe('bar');
expect(changed).toBeFalsy();
});
});
});

0 comments on commit 4537b9f

Please sign in to comment.