jquery rebinding event

1.5k Views Asked by At

I am trying to rebind the keydown event on focusout. Not really sure how what to pass to the keydown when rebinding. I tried passing this, but had no luck.

Anyone? Thanks

$('input.text').bind({
            click : function(e) { 

            },focusin : function(e) {

            },focusout : function() {
                // rebind keydown
                            // $(this).bind('keydown', this);
            },keydown : function() {
                $(this).unbind('keydown');
            }
2

There are 2 best solutions below

0
Rob W On BEST ANSWER

You have to save a reference to the function. By saving a reference to the function, you can rebind the original function:

var keydown_func = function() {
    $(this).unbind('keydown');
};
$('input.text').bind({
    click : function(e) { 

    },focusin : function(e) {

    },focusout : function() {
        // rebind keydown
        $(this).bind('keydown', keydown_func);
    },keydown : keydown_func
}
0
marxus On

one of the possible solutions is to define the event function before calling the bind method on the element, and then reuse it to rebind when you focusout. it goes something like this:
(this code should work...)

keyDownFn = function() {
    console.log('this will happen only on the first keydown event!');
    $(this).unbind('keydown')
}

$('input.text').bind({
    click: function(e) {},
    focusin: function(e) {},
    focusout: function() { $(this).bind('keydown', keyDownFn); },
    keydown: keyDownFn
})

enjoy.