Add a third "context" argument to Backbone.Event.Bind which, when passed, will bind the callback to the provided context.

Example:

	Backbone.Event.Bind('event', this.event, this);

Before this commit the way to do this was as follows:

	Backbone.Event.Bind('event', _.bind(this.event, this));
This commit is contained in:
Keith Cirkel
2011-07-25 11:50:56 +01:00
parent 77239753e1
commit 6ef6f759b6
2 changed files with 20 additions and 4 deletions

View File

@@ -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;
},
@@ -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;
}
@@ -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);
}
}
}

View File

@@ -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');
});
});