Search code examples
jqueryeventsdestroy

How to destroy jquery event in the Handle of the same event


I would like destroy a event after the same event is fired.

What is the best solution ?

var callback = function(){

    $('#myElement').off('click', callback)

    // do stuff
}

$('#myElement').on('click', callback);

I do not like having to specify repeatedly $('#myElement') and callback.


Solution

  • use namespace based event registration here

    var callback = function(){
    
        this.off('click.mycallback')
    
        // do stuff
    }
    
    $('#myElement').on('click.mycallback', callback);
    

    Or if you want to handler only once then use .one()

    $('#myElement').one('click', callback);