Code example:
var Events = $({});
Events.on('myCustomEvent', function(){ console.log('myCustomEvent 1') })
Events.trigger('myCustomEvent'); // I want notify the previous binds and all binds in future
$.ajax({...}).success(function(res){
Events.on('myCustomEvent', function(){ console.log('myCustomEvent 2') })
});
// when ajax or other long process will be finished 'myCustomEvent' must be fired
‘myCustomEvent 1’ will be printed because its binded before trigger will called and
‘myCustomEvent 2’ must be trigged too
Is it any solutions in jQuery?
Looks like what you want is not so much events as it is a pub/sub system, or code which implements the Observer pattern. Most of these implementations do not have the ability to retroactively call subscribers, after a message has been published. I’ve done it, but you need to be careful that anyone using the system knows a message may be published many times. Unfortunately, I can’t share the code, since it’s owned by my employer.
Just doing a search for “observer pattern in JavaScript” or “pubsub in JavaScript” will get you a good library. Typically these use a hash of a “topic” to an array of functions which are called when that topic is published. The trick is to also keep a history of when publish is called. When someone subscribes to a topic which is already published, re-publish that topic.
Hopefully that’s enough to get you started.