Tom Rider
Tom Rider

Reputation: 2815

How to rebind the events in jquery

I have some events like click, dblclick that are attached on large number of elements. To unbind click and dblclick events with all the elements at once I used this in jquery :

 $(document).unbind("click").unbind("dblclick");

Now I have to rebind these events to all the elements again. For this I used :

 $(document).bind("click").bind("dblclick");

But this is not working. Events are not rebind. How can I do this?

Upvotes: 0

Views: 4742

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

The best way is to name the callback functions, just as @adeneo suggested. But sometimes you don’t know when the handlers are bound (f.ex in a plugin), or perhaps you added anonymous callbacks using something like:

$(document).click(function() {
    // anonymous
});

then you can restore all those callbacks using the $._data object. Here is a function for you:

function restoreHandlers(elem, type) {
  var orig = $._data(elem, 'events');
  if ( type in orig ) {
    return $.map(orig[type], function(o) {
      return o.handler;
    });
  } else return [];
}

Use it like this (before you unbind):

var handlers = restoreHandlers(document, 'click');

then unbind:

$(document).off('click');

then rebind:

$.each(handlers, function(i, fn) {
    $(document).on('click', fn);
});

Upvotes: 0

adeneo
adeneo

Reputation: 318302

unbind:

$(document).off("click", myFunction);

bind:

$(document).on("click", myFunction);

function myFunction() {
    alert('you clicked the document');
}

jQuery on() and off() would be the way to go, and when rebinding, the function would have to be passed in again, you can't just rebind and expect it to know what function to call.

Upvotes: 1

Emil Ivanov
Emil Ivanov

Reputation: 37643

$(document).bind("click").bind("dblclick");

I don't think this will bind anything, you need callbacks.

$(document).bind("click", onClick).bind("dblclick", onDbClick);

Also, in this case you might want to consider using namespaced events:

$(document).bind("click.myclick", onClick)

And then later unbind only this event, leaving the other click untouched.

$(document).unbind("click.myclick");

P.S. It's now considered better practice to use the new on, off methods for binding.

Upvotes: 3

Related Questions