Search code examples
jquerypluginsdestroy

How to unbind non-custom events in a jQuery plugin


I'm doing a plugin and I have a few events like this one:

$(window).on('load resize', function(event) {
    _plugin.methodCall();
});

Also a $(document).on('click', function(){}); event. How do I unbind these in my destroy function without messing other user-defined events?

Or is it better to get creative with custom events?


Solution

  • You can use jQuery .off in combination with namespaces when attaching event with ".on"

        var validate = function() {
              // Code to validate form entries
            };
    
            // Delegate events under the ".validator" namespace
            $( "form" ).on( "click.validator", "button", validate );
    
            $( "form" ).on( "keypress.validator", "input[type='text']", validate );
    
            // Remove event handlers in the ".validator" namespace
            $( "form" ).off( ".validator" );