'Fire a custom event with JavaScript (or jQuery) when my function finishes

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?



Solution 1:[1]

$('#foo').on('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

Source: http://api.jquery.com/trigger/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel A. González