Orkun
Orkun

Reputation: 7228

passing parameters to on event callback

I think I am missing some fundamentals of javascript events.

Can smb please explain why these two calls don't return the same result?

// 1
$(window).on('load', function(){
    spiderLoad();
});

and

// 2
$(window).on('load', spiderLoad); 

EDIT:

function spiderload() {} 

function takes no params but I use some $jQuery to get values from data, href...etc. I am suspecting that I am losing the load event object reference, when calling spiderLoad as in 1.

Thanks

Upvotes: 0

Views: 293

Answers (2)

tcigrand
tcigrand

Reputation: 2397

If spiderLoad is returning a value, they will act differently.

function spiderLoad(){
    return false
}

They would be the same (assuming the function doesn't care what arguments are passed in) if it was written like this.

$(window).on('load', function(){
    return spiderLoad();
});

Upvotes: 2

solarshado
solarshado

Reputation: 566

They have different results because they are doing fundamentally different things.

$(window).on('load', function(){
    spiderLoad();
});

This creates a new, anonymous function and adds it as a event handler. The anonymous function calls spiderLoad() with no arguments.

$(window).on('load', spiderLoad); 

This adds spiderLoad() as directly as an event handler, meaning it will receive a jQuery event object as its first parameter.

EDIT: if spiderLoad() takes no arguments, there there should be no difference, except perhaps value of this inside spiderLoad()

Upvotes: 4

Related Questions