Jay
Jay

Reputation: 3531

Passing anonymous function to custom event trigger in Javascript/jQuery

I'm trying to trigger custom events on DOM elements and pass anonymous functions to be executed when the event is triggered (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");
    }
});

So clicking on "some-button" should trigger "custom_event" on "some-dom" and cause the anonymous function that I passed on the trigger to be executed. Right? But the browser says that callback is undefined in the custom event. Am I doing something wrong? Is passing anonymous functions as trigger arguments not allowed? Thanks

Upvotes: 4

Views: 6281

Answers (2)

Shef
Shef

Reputation: 45589

You can do it like this:

$('#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.

Upvotes: 0

user113716
user113716

Reputation: 322592

You need to pass multiple extra arguments to trigger() as an Array. (One argument can be passed without the 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/

Upvotes: 7

Related Questions