views:

42

answers:

1

Say I have the following jQuery:

$('#myelement').bind('click', foo);

How can I unbind this event without using jQuery?

The event doesn't show up in any of these methods on a DOM element:

var domElement = document.getElementById('myelement');
domElement.onclick // == null
domElement.click // == undefined

So how can I unbind it without using jQuery such as the following?

$('#myelement').unbind()
+2  A: 

If you're using a recent version of jQuery, this will work:

delete $.cache[document.getElementById("myelement")[$.expando]].events.click;

You can test it here.

Note that it's not a complete cleanup, you can use jQuery's .removeEvent() implementation for that, if you want to clear all handlers.

Nick Craver
Imagine a world without jQuery... :)
Alec
This works. Isn't it better to use the `jQuery` variable instead of `$` though? Also, isn't there a way to disable jQuery's hook into the events of an element?
Senseful
@Senseful - Either variable works, I used `$` for brevity, use jQuery to be safe :) For the second question...I'm not sure what you're asking, you want to prevent it binding in the first place?
Nick Craver
Note that this approach **is** using jQuery. If you're going to "use" jQuery anyway, why not just unbind the handler with the direct API? It's just going to do what this suggests anyway.
Pointy
@Pointy - There's no way to *not* use the actual jQuery object, since the handlers themselves are stored in `jQuery.cache`, if `jQuery` isn't there, you don't need this code at all...since nothing was bound. However, it is a valid point that *if* jQuery is present, why *not* just use `.unbind()`?
Nick Craver
@Nick oh I totally understand, and I agree completely. That's kind-of my point. I also understand the original question, but the fact is that because the "binding" is an internal thing with jQuery-managed resources, it makes no sense to do it without jQuery.
Pointy
I think if DOM3 EventListenerList gets implemented, we might be able to do it without jQuery.
livibetter
@livbetter well maybe that'd be true if jQuery altered its event handling system.
Pointy