Arjun
Arjun

Reputation: 6729

jquery: pass an object to event handler using jquery trigger method

Following code for passing an object to event handler is not working:

$('a.another').live('click', function(e, data) {
        alert(data); // **alerts '[{isMachineClick:true}]'**
        alert(data.isMachineClick); // **alerts 'undefined'**
});

$('a.another').trigger('click', "[{isMachineClick:true}]");

Please have a look at this.

PS: solution provided at link pass an object through jquery trigger is not working, so posting a new thread.

Upvotes: 4

Views: 5558

Answers (1)

Luke Dennis
Luke Dennis

Reputation: 14550

You're passing only a string, and what's more the JSON inside the string is an array, not an object. Try this:

$('a.another').live('click', function(e, data) {
    alert(data[0].isMachineClick);
});

$('a.another').trigger('click', [{isMachineClick:true}]);

UPDATE: Didn't realize how this worked: using an array is correct, and each additional item becomes another argument. This is the correct code:

$('a.another').live('click', function(e, data, data2) {

    alert(data.isMachineClick);

    alert(data2.someOtherThing);
});

$('a.another').trigger('click', [{isMachineClick:true}, {someOtherThing:false}]);

Upvotes: 6

Related Questions