user1477388
user1477388

Reputation: 21430

Pass object as parameter

I have the following code:

$('.helloWorld').on('click', function() {
    $(this).css('background', 'black'); 
});

Instead, I would like to do something like this (for research):

var params = [
    'click',
    function () {
        $(this).css('background', 'black');
    }
];

$('.helloWorld').on(params);

I get an error that reads, "Uncaught SyntaxError: Unexpected token , ."

Is this possible? If so, how?

Upvotes: 1

Views: 65

Answers (2)

sma
sma

Reputation: 9597

You are using an array in your example. Use an object instead ({} instead of []) Something like this should work:

var params = {
    "event" : 'click',
    "callback" : function () {
        $(this).css('background', 'black');
    }
};

$('.helloWorld').on(params.event, params.callback);

Upvotes: 3

Paul
Paul

Reputation: 141829

You can use apply to call a function using an array as the arguments, you need to specify the thisArg though:

$.fn.on.apply( $('.helloWorld'), params );

Upvotes: 4

Related Questions