Skip to content

Commit f9a096a

Browse files
committed
listenTo equivalents for Commands and Requests.
1 parent 1ceb392 commit f9a096a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/backbone.radio.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,25 @@ Radio.Commands = {
233233
}
234234
};
235235

236+
// listenTo equivalent for Commands
237+
var listenMethods = {complyFor: 'comply', complyForOnce: 'complyOnce'};
238+
_.each(listenMethods, function(implementation, method) {
239+
Radio.Commands[method] = function(obj, name, callback) {
240+
var listeningTo = this._listeningTo || (this._listeningTo = {});
241+
var id = obj._listenId || (obj._listenId = _.uniqueId('c'));
242+
listeningTo[id] = obj;
243+
if (!callback && typeof name === 'object') { callback = this; }
244+
if (implementation === 'once') {
245+
callback = _.compose(function(result) {
246+
this.stopListening(_.rest(arguments));
247+
return result;
248+
}, callback);
249+
}
250+
obj[implementation](name, callback, this);
251+
return this;
252+
};
253+
});
254+
236255
//
237256
// Backbone.Radio.Requests
238257
// A messaging system for requesting data.
@@ -322,6 +341,25 @@ Radio.Requests = {
322341
}
323342
};
324343

344+
// listenTo equivalent for Requests
345+
var listenMethods = {replyFor: 'reply', replyForOnce: 'replyOnce'};
346+
_.each(listenMethods, function(implementation, method) {
347+
Radio.Requests[method] = function(obj, name, callback) {
348+
var listeningTo = this._listeningTo || (this._listeningTo = {});
349+
var id = obj._listenId || (obj._listenId = _.uniqueId('r'));
350+
listeningTo[id] = obj;
351+
if (!callback && typeof name === 'object') { callback = this; }
352+
if (implementation === 'once') {
353+
callback = _.compose(function(result) {
354+
this.stopListening(_.rest(arguments));
355+
return result;
356+
}, callback);
357+
}
358+
obj[implementation](name, callback, this);
359+
return this;
360+
};
361+
});
362+
325363
//
326364
// Backbone.Radio.channel
327365
// Get a reference to a channel by name.

0 commit comments

Comments
 (0)