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?
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With