mirror of
https://github.com/jashkenas/backbone.git
synced 2026-04-30 03:00:06 -04:00
implement listenToOnce via listenTo
This commit is contained in:
52
backbone.js
52
backbone.js
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user