Instead of having nested callbacks in JS, I would like to fire and listen to my own custom events. I don't need or want to access the DOM. Here's an example:
function doSomething(){
//...
$.trigger('finished-doSomething'); //fire the event 'finished-doSomething'
}
//when the event 'finished-doSomething' is fired -> execute the function in the second param
$.live('finished-doSomething', function(){
alert("I finished-doSomething");
});
Would it be possible to do that with normal JavaScript code or with a library like jQuery? If not, what's a good approach to avoid nested callbacks?
Well, you can use custom events on some common element, say document.body
.
// Subscribe
$(document.body).on('nifty.event', function() {
// Handle it
});
// Publish
$(document.body).trigger('nifty.event');
Gratuitous live example | source
Or for complete disconnection from the DOM, there are a couple of pub/sub jQuery plug-ins, like this one.