简体   繁体   中英

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?

Thanks!

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM