Search code examples
javascriptjqueryeventswidgetlive

How to remove all jquery live events from javascript widget


I'm developing some javascript widget which loaded on many other sites.

When widget are loading I bind jquery live event on links and buttons. For instance:

$('.my-submit').live('click', function() {...});
...
$('.my-link').live('click', function() {...});

So the question is how can I remove all live events only for widget links and buttons?


Solution

  • The simple way to do this is to bind with a namespace, and remove all the namespaced events:

    $('.my-submit').live('click.myPlugin', function() {...});
    

    You can then call die with the namespace:

    $('.my-submit').die('click.myPlugin'); // only myPlugin events are removed
    

    Better yet is to use the on and off functionality introduced in jQuery 1.7. This is a far superior way to handle binding and unbinding events:

    $(document).on('click.myPlugin', '.my-submit', function() {...}))
               .on('click.myPlugin', '.my-link', function() {...}));
    
    $(document).off('click.myPlugin'); // remove all myPlugin functions