What is an easy way to define some jQuery.Callbacks () prerequisites?

What is the easiest way to define a few 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 that each function added is added to another function that checks the status of each of them (), although this seems like a fairly common scenario, maybe an easier way that I miss.

+4
source share
1 answer

I think deferred is what you are 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_callback will be called only when some_promise and another_promise were allowed.

deferred basically just adds an abstraction layer to your asynchronous functions, making it easy to express dependencies. I assume your example will look like this:

 // simple pubsub example var pubsub=(function() { var callbacksObj={}; return function(id){ if(!id) throw 'callbacks requires an id'; return some_assynchrnous_function(id); // like $.ajax }; })(); function fn1(){ console.log('fn1'); }; function fn2(){ console.log('fn2'); }; function fn3(){ console.log('fn3'); }; // subscribing var foo = pubusb('foo'); // should return a deferred/promise var bar = pubsub('bar'); $.when(foo).then(fn1); $.when(bar).then(fn2); $.when(foo, bar).then(fn3); 

I'm not quite sure if this is correct for jQuery, but you get the idea. I did not find the jQuery API to make a lot of sense to me, so I wrote my own: 3

It’s useful for me to be able to make β€œempty” deferred objects, and then attach the done handler to it, and then transfer the deferred object to something that ultimately leads to its resolution. I'm not sure jQuery can do this.

At first, this may seem like a bit of a challenge, but if you can wrap your head around yourself, you can get so much value out of it. The dependencies are large, but the overview is also good, you can add several done handlers at several levels, one handler can process the actual data, one handler may just be interested when the handler ends so you can show the loading bar, etc.

+1
source

Source: https://habr.com/ru/post/1383221/


All Articles