implement listenToOnce via listenTo

This commit is contained in:
Adam Krebs
2014-10-27 11:06:25 -04:00
parent a7587d7260
commit d61ab4d2e9

View File

@@ -228,37 +228,35 @@
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
if (implementation === 'once') {
if (typeof name === 'object') {
_.each(name, function(cb, event) {
name[event] = function() {
this.stopListening(obj, event, cb);
return cb.apply(this, arguments);
}
});
} else {
var cb = callback;
callback = function () {
this.stopListening.apply(this, obj, name, cb);
return cb.apply(this, arguments);
};
Events.listenTo = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj.on(name, callback, this);
return this;
};
Events.listenToOnce = function(obj, name, callback) {
if (typeof name === 'object') {
_.each(name, function(cb, event) {
name[event] = function() {
this.stopListening(obj, event, cb);
return cb.apply(this, arguments);
}
}
obj.on(name, callback, this);
return this;
};
});
});
} else {
var cb = callback;
callback = function () {
this.stopListening.apply(this, obj, name, cb);
return cb.apply(this, arguments);
};
}
return this.listenTo(obj, name, callback);
}
// Aliases for backwards compatibility.
Events.bind = Events.on;