Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Paul Knopf Avatar asked Nov 17 '09 18:11

Paul Knopf


3 Answers

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)
like image 153
jsonx Avatar answered Oct 07 '22 13:10

jsonx


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);
});
like image 11
bdukes Avatar answered Oct 07 '22 12:10

bdukes


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.

like image 4
Sam R Avatar answered Oct 07 '22 11:10

Sam R