I am trying to bind an event to a textbox
that contains parameters. The following keep looks as if it should do it, but every time the page loads, it gets executed.
jQuery(function(){
jQuery('#textbox').bind('click', EventWithParam('param'));
});
The event gets called with that parameter every time the page loads. This may not work because events with parameters are not supported. If so, is there another route?
You can pass event parameters as second arguments to bind(). It is not direct callback parametes but maybe you would like to use it:
From jQuery documentation: bind
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
To bind a function that takes parameters, use an anonymous function to act as a closure over the parameters.
jQuery(function($) {
var param = 'text';
$('#textbox').click(function() {
EventWithParam(param);
// or just use it without calling out to another function
$(this).text(param);
});
});
Your example is executing the EventWithParam
function, and then trying to bind to the result of that function call.
Calling unbind
without specifying a function will unbind all handlers for the specified type of event (including the anonymous function). If you want to unbind that function specifically, you'll need to provide it with a name, like this:
jQuery(function($) {
var param = 'text',
clickCallback = function() {
EventWithParam(param);
// or just use it without calling out to another function
$(this).text(param);
};
$('#textbox').click(clickCallback);
});
bdukes is exactly right. I'm adding my response as I've recently found something interesting having to do with jQuery's bind/unbind function and anonymous functions, its event name spaces. Previously shown above the bind event is called as follows.
jQuery('#textbox').bind('click',function(){EventWithParam('param')});
To unbind this even the user must call ...
jQuery('#textbox').unbind('click');
In effect, removing all onClick events.
Now comes in jQuery name spaces. If you have an anonymous function you wish to attach to the click event and later unbind do it as follows.
jQuery('#textbox').bind('click.yourNameSpace',function(){EventWithParam('param')});
Then to unbind simple call the unbind function as follows.
jQuery('#textbox').unbind('click.yourNameSpace');
The rest of your onClick events will remain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With