Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
cnandreu Avatar asked Jun 22 '12 22:06

cnandreu


People also ask

What function do we invoke to fire a custom event in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements.

What is the jQuery method for attaching a custom event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

What is fire event in JavaScript?

Browser support: Initializes an event object and dispatches it to the current element. To create an event object, use the createEventObject method in Internet Explorer. The created event can be passed as a second parameter of the fireEvent method.


1 Answers

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.

like image 91
T.J. Crowder Avatar answered Nov 14 '22 22:11

T.J. Crowder