Skip to content

Commit

Permalink
Merge pull request jashkenas#500 from keithcirkel/master
Browse files Browse the repository at this point in the history
  • Loading branch information
jashkenas committed Jul 26, 2011
2 parents d8ef258 + 6ef6f75 commit 49a16bd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
8 changes: 4 additions & 4 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@

// Bind an event, specified by a string name, `ev`, to a `callback` function.
// Passing `"all"` will bind the callback to all events fired.
bind : function(ev, callback) {
bind : function(ev, callback, context) {
var calls = this._callbacks || (this._callbacks = {});
var list = calls[ev] || (calls[ev] = []);
list.push(callback);
list.push([callback, context]);
return this;
},

Expand All @@ -89,7 +89,7 @@
var list = calls[ev];
if (!list) return this;
for (var i = 0, l = list.length; i < l; i++) {
if (callback === list[i]) {
if (list[i] && callback === list[i][0]) {
list[i] = null;
break;
}
Expand All @@ -114,7 +114,7 @@
list.splice(i, 1); i--; l--;
} else {
args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
callback.apply(this, args);
callback[0].apply(callback[1] || this, args);
}
}
}
Expand Down
16 changes: 16 additions & 0 deletions test/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,21 @@ $(document).ready(function() {
equals(obj.counterA, 1, 'counterA should have only been incremented once.');
equals(obj.counterB, 1, 'counterB should have only been incremented once.');
});

test("Events: bind a callback with a supplied context", function () {
expect(1);

var TestClass = function () { return this; }
TestClass.prototype.assertTrue = function () {
ok(true, '`this` was bound to the callback')
};

var obj = _.extend({},Backbone.Events);

obj.bind('event', function () { this.assertTrue(); }, (new TestClass));

obj.trigger('event');

});

});

0 comments on commit 49a16bd

Please sign in to comment.