4

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

2 Answers 2

7

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Right you are! How did I miss that! Thanks :)
@Jayraj & @user113716 I am doing the same as shown in answer but I get error on console as NS_ERROR_XPC_SECURITY_MANAGER_VETO: alert("this is my anonymous function passed as event data"); Why? I only changed that I have used on instead of live to register custom event
It's impossible to say what's wrong without seeing some sample code. Maybe you could try creating a new question? Also, given that this answer is over 4 years old, it's possible that there have been API changes in jQuery.
0

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.

1 Comment

Well yes, using a named function would work too. I wanted to use an anonymous function for terseness but didn't realize I had to pass arguments in an array. Thanks. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.