Reputation: 2312
Is there an alternative in angular of jquery $.Callbacks? I want a simple way to to manage callback lists in angular. I want to do the following in angular:
function Broadcast(){
var self= this;
this._statusRecivedCallbacks = $.Callbacks();
setTimeout(function () {
self._statusRecivedCallbacks.fire('arg1', 'arg2');
}, 500);
}
Broadcast.prototype.onStatusRecived = function(callback){
if($.isFunction(callback)){
this._statusRecivedCallbacks.add(callback);
}
}
var broadObj = new Broadcast();
//subscribe to this for example in a controller
broadObj.onStatusRecived(function(arg1, arg2){
alert('the argument 1 is: ' + arg1 + ' and the argumet 2 is: ' + arg2);
});
//subscribe to this for example in a directive
broadObj.onStatusRecived(function(arg1, arg2){
alert("I'am suscribe too");
});
code: http://jsfiddle.net/w0hmqbea/6/
If is there not an alternative in angular, is there an alternative in lodash, underscore or any other crosscutting framework? Perhaps i can do something similar with promises, any idea? But I do not want to do then().then()
, because I will subscribe to the event in different places like for example in a controller an a directive.
I'm looking for an explicit way and easy to follow, to subscribe to an event in different places like $.Callbacks but in angular without jquery dependency.
For example pubsub is not easy to follow when many objects are suscribe to the same event. And I don't know any way/technique to subscribe to the same event in many objects with promises.
Upvotes: 1
Views: 244
Reputation: 193271
Angular doesn't have anything specific for PubSub implementation. As Promises are concerned, I don't think this is correct to compare them with what $q
service can offer, because they sort of serve different purposes. After all, Promises are not really the pattern to replace PubSub and it's definitely not about events and callbacks.
If your purpose is to write more transparent version of PubSub pattern without jQuery then you can do something like this with pure Javascript.
function Broadcast() {
var self = this;
this._statusRecivedCallbacks = [];
setTimeout(function () {
self.fire('arg1', 'arg2');
}, 500);
}
Broadcast.prototype.onStatusRecived = function (callback) {
if (angular.isFunction(callback)) {
this._statusRecivedCallbacks.push(callback);
}
}
Broadcast.prototype.fire = function() {
var args = arguments ;
this._statusRecivedCallbacks.forEach(function(callback) {
callback.apply(null, args);
});
};
var broadObj = new Broadcast();
broadObj.onStatusRecived(function (arg1, arg2) {
console.log(arg1)
alert('the argument 1 is: ' + arg1 + ' and the argumet 2 is: ' + arg2);
});
broadObj.onStatusRecived(function (arg1, arg2) {
alert("I'am suscribe too");
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Upvotes: 1