jQuery global event

Simple and easy. Took me about 5 minutes to figure that jQuery could do this.

$("#A").on("click", function(){
    $(document).trigger("custom");
});
$(document).on("custom", function(e){
    $("#B").removeClass("hidden");
});
$(document).on("custom", function(e){
    alert("something");
});

Best to namespace events, use jQuery’s namespacing or on your own (examples below).

I used it for something more like this:

$(document).trigger('paymentmethod:successfulSave');
$(document).trigger('paymentmethod:cancel');

$(document).on('paymentmethod:successfulSave', function(){
    console.log('save');
    //refresh payment methods
});

$(document).on('paymentmethod:cancel', function(){
    console.log('cancel');
});

http://stackoverflow.com/questions/23782786/jquery-trigger-custom-global-event



Leave a Reply

Your email address will not be published. Required fields are marked *