Moving Javascript object with all bounded events to other variable

Posted by Saif Bechan on Stack Overflow See other posts from Stack Overflow or by Saif Bechan
Published on 2012-04-15T11:17:12Z Indexed on 2012/04/15 11:29 UTC
Read the original article Hit count: 196

Filed under:
|

Let's say I have an anchor tag, with some events.

<a id="clickme" href="/endpoint">clickme</a>
<a id="clickme2" href="/endpoint2">clickme2</a>

Let's use jquery for simplicity:

$('#clickme').on('click', function(){.....})

I also have a variable:

var myActiveVar = $('#clickme');

When I want to remove the element an every trace of it I can do this:

myActiveVar.off().remove();

Here comes the problem, I want to reuse the variable. Something like this:

var oldAcriveVar = myActiveVar;
    myActiveVar  = $('#clickme2');

// Now I want to do some operations
// both of the elements are still on 
// the page, when I'm done:

oldActiveVar.off().remove();

Comeplete code:

var myActiveVar  = $('#clickme');

// Operate on myActiveVar

var oldAcriveVar = myActiveVar;
    myActiveVar  = $('#clickme2');

// Operate on myActiveVar which is
// the new element.
// Old element stays visible

oldActiveVar.off().remove();

// Old element and all traces are gone

Edit:

Maybe the above code will work, but my problem goes beyond. I just gave a simplified example.

I am using Backbone events that are bounded to object. They need to be removed when I am done with the object.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery