Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

jQuery unbind events declared in scope

I've got some object that creates some event attached to document. They are common events like mousemove, mousedown etc.

Then I want to make $(document).unbind('mousemove') and its ok but it may crash some events created by end user of plugin or cause conflicts with some external code.

Is it possible to remove all events declared inside some scope only?

Like:

$.fn.somePlugin = function() {
    //here begins our scope

    //declaring a lot of events

    //some stuff

    //remove events of this scope leaving other of same type untouched
}

Or is there any other way of managing groups of events?

Upvotes: 0

Views: 303

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use namespaced event handlers

Ex

$(el).on('click.myplugin', function(){...})//or any eventname.pluginname

then

$(el).off('click.myplugin')

Demo: Fiddle

Upvotes: 3

gingerbreadboy
gingerbreadboy

Reputation: 7769

Pass a reference to the function to the off method.

From http://api.jquery.com/off/

var foo = function() {
  // Code to handle some kind of event
};

// ... Now foo will be called when paragraphs are clicked ...
$( "body" ).on( "click", "p", foo );

// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );

Upvotes: 0

Related Questions