Search code examples
javascriptjqueryjquery-1.4

How to prevent multiple duplicate events from being registered?


I have a situation where a .js library is registering a mouseup event to a DOM element. The DOM element is removed, and replaced and the event is re-registered. This causes two duplicate events to be registered. Here is a reproduction for example:

Please Note: This is using jQuery version 1.4.4

<div id="top">
 <div id="nested">
  <div id="stranded">
   Alien Code
  </div>
 </div>
</div>​

<script type="text/javascript">
 function addLive(){
  $("#stranded").live("mouseup",
   function (e) {
    var node = document.getElementById("stranded");
    var nodeCopy = $(node).clone(true)[0];
    var tar  = document.getElementById("nested");
    tar.appendChild(nodeCopy);
   }
  );
 }
 addLive();
 addLive();
</script>

Also, here is a jsFiddle: http://jsfiddle.net/3zbtK/

How can I prevent the second call to addLive from registering the mouse event if one already exists?


Solution

  • function addLive(){
     $("#stranded").die("mouseup");
     $("#stranded").live("mouseup",
      function () {
       var node = document.getElementById("stranded");
       var nodeCopy = $(node).clone(true)[0];
       var tar  = document.getElementById("nested");
       tar.appendChild(nodeCopy);
     }
    );
    }