0

This is more a learning piece for me around how event listeners bound to jQuery selectors are handled.

So say I have the following code:

<html>
<div class = "one">one</div>
<div class = "two">two</div>
</html>

<script>
$(".one").click(function() {
$(this).removeClass("one").addClass("two");
console.log("one");
})
$(".two").click(function() {
console.log("two");
})

</script>

On the first click of one, the selector is no longer valid (as the class is now two instead of one). However the event is still bound to this element. This element will also not fire the ".two" handler as this has already been bound.

What would be the easiest way to unbind a handler with the initial click and then rebind afterwards?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ash
  • 424
  • 6
  • 26

2 Answers2

2

Bind the events on the document, no need to unbind and rebind the events.

$(document).on("click", ".one", function() {
    $(this).removeClass("one").addClass("two");
    console.log("one");
});

$(document).on("click", ".two", function() {
    console.log("two");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">one</div>
<div class="two">two</div>
eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • this is really interesting.. could you give a brief explanation as to why this method works? – Ash Aug 05 '16 at 11:16
  • This is a *live binding*, it is even working on changed or new elements. It is more dynamic a static element bindings, where you would have to bind it over and over again. @Ash – eisbehr Aug 05 '16 at 11:30
1
$(".one").unbind("click");
$(".one").bind("click", fn);

You can use unbind() to remove an event added with bind() (or binded like above)

https://jsfiddle.net/7yn7apte/ No re-binding

https://jsfiddle.net/7yn7apte/1/ Re-binding

Well, this answer your question. But, you'd better use on() and off() as bind() calls on() and unbind() calls off().

You can find a more exhaustive explanation here https://stackoverflow.com/a/9113835/6341631

Community
  • 1
  • 1
Gregoire
  • 749
  • 6
  • 15