mirror of
https://github.com/jashkenas/backbone.git
synced 2026-04-30 03:00:06 -04:00
allow context as 4th parameter of stopListening
This commit is contained in:
@@ -191,25 +191,26 @@
|
||||
// An inversion-of-control version of `on`. Tell *this* object to listen to
|
||||
// an event in another object ... keeping track of what it's listening to.
|
||||
listenTo: function(object, events, callback, context) {
|
||||
context = context || this;
|
||||
var listeners = this._listeners || (this._listeners = {});
|
||||
var id = object._listenerId || (object._listenerId = _.uniqueId('l'));
|
||||
listeners[id] = object;
|
||||
context = context || this;
|
||||
object.on(events, callback || this, context);
|
||||
return this;
|
||||
},
|
||||
|
||||
// Tell this object to stop listening to either specific events ... or
|
||||
// to every object it's currently listening to.
|
||||
stopListening: function(object, events, callback) {
|
||||
stopListening: function(object, events, callback, context) {
|
||||
contxt = context || this;
|
||||
var listeners = this._listeners;
|
||||
if (!listeners) return;
|
||||
if (object) {
|
||||
object.off(events, callback, this);
|
||||
object.off(events, callback, context);
|
||||
if (!events && !callback) delete listeners[object._listenerId];
|
||||
} else {
|
||||
for (var id in listeners) {
|
||||
listeners[id].off(null, null, this);
|
||||
listeners[id].off(null, null, context);
|
||||
}
|
||||
this._listeners = {};
|
||||
}
|
||||
|
||||
@@ -89,10 +89,27 @@ $(document).ready(function() {
|
||||
test("listenTo with context", 1, function() {
|
||||
var a = _.extend({}, Backbone.Events);
|
||||
var ctx = {};
|
||||
a.listenTo(a, 'foo', function(){ equal(ctx, this); }, ctx);
|
||||
a.listenTo(a, 'foo', function(){ equal(this, ctx); }, ctx);
|
||||
a.trigger('foo');
|
||||
});
|
||||
|
||||
test("stopListening with context", 2, function() {
|
||||
var a = _.extend({}, Backbone.Events);
|
||||
var ctx = {};
|
||||
var calledWithContext = false;
|
||||
var calledWithoutContext = false;
|
||||
|
||||
a.listenTo(a, 'foo', function(){ calledWithContext = true; }, ctx);
|
||||
a.listenTo(a, 'foo', function(){ calledWithoutContext = true; });
|
||||
|
||||
a.stopListening(a, 'foo', null, ctx);
|
||||
|
||||
a.trigger('foo');
|
||||
|
||||
equal(false, calledWithContext);
|
||||
equal(true, calledWithoutContext);
|
||||
});
|
||||
|
||||
test("trigger all for each event", 3, function() {
|
||||
var a, b, obj = { counter: 0 };
|
||||
_.extend(obj, Backbone.Events);
|
||||
|
||||
Reference in New Issue
Block a user