Passing an anonymous function to a custom event trigger in Javascript / jQuery

I am trying to trigger custom events in DOM elements and pass anonymous functions that will be executed when the event fires (using jQuery). So something like this:

$(some-dom).live("custom_event", function(evtObj, data, callback) { //do some stuff callback(); }); $(some-button).click(function() { $(some-dom).trigger("custom_event", some_data, function () { alert("this is my anonymous function passed as event data"); } }); 

Thus, pressing the "some-button" button should start "custom_event" in "some-dom" and call the anonymous function that I passed to the trigger. Right? But the browser says the callback is undefined in the user event. Am I doing something wrong? Skips anonymous functions since trigger arguments are not allowed? Thanks

+4
source share
2 answers

You need to pass a few extra arguments to trigger() as an array. (One argument can be passed without an array.)

 $(some-dom).click(function() { // v-----pass extra args in an Array $(some-dom).trigger("custom_event", [some_data, function () { alert("this is my anonymous function passed as event data"); }]); // ^------Array }); 

Example: http://jsfiddle.net/NRSJ2/

+7
source

You can do it as follows:

 $('#testelement').live("test_event", function(e, myCallback) { myCallback(); }); $('#clickme').click(function(e){ e.preventDefault(); var myFunc = function () { alert("this is my anonymous function passed as event data"); }; $('#testelement').trigger('test_event', [myFunc]); }); 

Here is the proof of concept .

0
source

All Articles