Edvinas Pranka
Edvinas Pranka

Reputation: 81

How to assign events to variable

I want to assign events to variables, because I can't delete $('body').on('keyup') event with different callbacks (sorry for my English). It is impossible?

function test_1()
{
    $('body').on('keyup', function(e)
    {
        //do stuff 1
    }
}

function test_2()
{
    $('body').on('keyup', function(e)
    {
        //do stuff 2
    }
}
test_1();
test_2();

And now I want to delete the event listener who executes 'do stuff 2' on keypress.

I want to something like that:

var handler_1;
var handler_2;
function test_1()
{
    handler_1 = $('body').on('keyup', function(e)
    {
        //do stuff 1
    }
}

function test_2()
{
    handler_2 = $('body').on('keyup', function(e)
    {
        //do stuff 2
    }
}
function delete()
{
   handler_2.off();
}
test_1();
test_2();

And then I execute delete() I want that handler_2 will turn off the event. But when I press any key the 'do stuff 1' must be work.

Upvotes: 0

Views: 83

Answers (4)

Jonathan
Jonathan

Reputation: 9151

Use on / off

function handler1() {
    alert("I will fire!");
}

function handler2() {
    alert("I won't fire!");
}

$(document).on('keyup', handler1);

$(document).on('keyup', handler2);

$(document).off('keyup', handler2);

Fiddle

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15666

I would use name-spaced events. This allows you to assign a name to the event so that you can easily remove it later. Also, when you assign the result to handler_1, you are actually just getting back a jquery object representing the body element, so it would be equivalent to $('body'), so I don't think it's necessary.

function test_1()
{
   $('body').on('keyup.fn1', function(e)
    {
        //do stuff 1
    }
}

function test_2()
{
    $('body').on('keyup.fn2', function(e)
    {
        //do stuff 2
    }
}
function delete()
{
   $('body').off('keyup.fn2');
}
test_1();
test_2();

Upvotes: 3

beautifulcoder
beautifulcoder

Reputation: 11320

You should be able to use bind so for example:

var e1 = function () { ... },
    e2 = function () { ... };

$('#target').bind('keyup', e1);
$('#target').bind('keyup', e2);
$('#target').unbind('keyup', e1);
$('#target').unbind('keyup', e2);

Upvotes: 1

Russell Zahniser
Russell Zahniser

Reputation: 16354

It sounds like what you want is:

function keyup1(e)
{
    //do stuff 1
}
function test_1()
{
    $('body').on('keyup', keyup1);
}
function delete()
{
    $('body').off('keyup', keyup1);
}

See the first example in the documentation page for off().

Upvotes: 3

Related Questions