Skip to content

Commit

Permalink
Test that listenToOnce is only called once
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell authored and akre54 committed Nov 3, 2014
1 parent fab32cc commit 2450b70
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,10 @@
for (var event in name) this.listenToOnce(obj, event, name[event]);
return this;
}
var cb = function() {
var cb = _.once(function() {
this.stopListening(obj, name, callback);
callback.apply(this, arguments);
}
});
cb._callback = callback;
this.listenTo(obj, name, cb);
return this;
Expand Down
13 changes: 13 additions & 0 deletions test/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@
b.trigger('event2');
});

test("listenToOnce", 2, function() {
// Same as the previous test, but we use once rather than having to explicitly unbind
var obj = { counterA: 0, counterB: 0 };
_.extend(obj, Backbone.Events);
var incrA = function(){ obj.counterA += 1; obj.trigger('event'); };
var incrB = function(){ obj.counterB += 1; };
obj.listenToOnce(obj, 'event', incrA);
obj.listenToOnce(obj, 'event', incrB);
obj.trigger('event');
equal(obj.counterA, 1, 'counterA should have only been incremented once.');
equal(obj.counterB, 1, 'counterB should have only been incremented once.');
});

test("listenToOnce and stopListening", 1, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
Expand Down

0 comments on commit 2450b70

Please sign in to comment.