What’s the simplest way to define multiple jQuery.Callbacks() prerequisites?
// simple pubsub example
var pubsub=(function() {
var callbacksObj={};
return function(id){
if(!id) throw 'callbacks requires an id';
return (callbacksObj[id] = callbacksObj[id] || $.Callbacks('unique memory'));
};
})();
function fn1(){
console.log('fn1');
};
function fn2(){
console.log('fn2');
};
function fn3(){
console.log('fn3');
};
// subscribing
pubsub('foo').add(fn1);
pubsub('bar').add(fn2);
pubsub('foo','bar').add(fn3); // adding a function with multiple dependencies
// publishing
pubsub('foo').fire() // should only log 'fn1';
pubsub('bar').fire() // should log both 'fn2' AND 'fn3' since both have fired
I can see wrapping each added function in another function that checks each id’s fired() state, though this seems like a common enough scenario that perhaps there’s a simpler way I’m missing.
I think
deferredis what you’re looking for:http://api.jquery.com/category/deferred-object/
it looks like this:
$.when(some_promise).then(some_callback)And you can have:
$.when(some_promise, another_promise).then(some_callback)In this case
some_callbackwill only be called ifsome_promiseandanother_promisehave been resolved.deferredbasically just adds a level of abstraction to your asynchronous functions, making it easier to express the dependencies. I suppose your example would look like:I’m not entirely sure if this is correct for jQuery, but you get the idea. I didn’t find the jQuery API to make very much sense to me so I wrote my own :3
I find it useful to be able to make ’empty’ deferred objects, then attaching a
donehandler to it, then passing the deferred object along to something that will eventually end up resolving it. I’m not sure if jQuery can do this.It may seem a little daunting at first, but if you can wrap your head around it you can get so much awesomeness from this. Dependencies is a big one but scoping is also great, you can add multiple
donehandlers on multiple levels, one handler may handle the actual data, one handler may just be interested in when the handler finishes so you can show a loading bar etc.