Paul Knopf Paul Knopf - 5 months ago 26
jQuery Question

jQuery bind and unbind event with parameters

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?

Answer

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);
});
Comments