Reputation: 5091
I have a button on which I want to attach an event listener. I also need to pass a extra parameter url to this function. I read about apply
and I'm doing the following:
$('#list-button').on('click',postListing.apply([url]));
My problem is that as soon as this script is loaded postListing
is called. I am not calling the function anywhere else. I need it to be called only on click.
Upvotes: 0
Views: 1359
Reputation: 467
The difference between bind and call/apply is that bind doesn't call the function immediately much like it loads the data with the variable when needed
You can reformat your code so it looks like this
$('#list-button').on('click', postListing.bind(this, url));
Upvotes: 4
Reputation: 5091
Found a way. It can be done using a closure:
var postListing = function(event, url){
return function(){
//Main functionality wrapped here
};
};
And the event listener setting remains the same:
$('#list-button').on('click',postListing.apply([url]));
Upvotes: 0