Mootools - how to destroy a class instance

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-06-06T01:04:42Z Indexed on 2010/06/06 1:12 UTC
Read the original article Hit count: 501

Filed under:
|
|

What I'm trying to do is create a class that I can quickly attach to links, that will fetch and display a thumbnail preview of the document being linked to. Now, I am focusing on ease of use and portability here, I want to simply add a mouseover event to links like this:

<a href="some-document.pdf" onmouseover="new TestClass(this)">Testing</a>

I realize there are other ways I can go about this that would solve my issue here, and I may end up having to do that, but right now my goal is to implement this as above. I don't want to manually add a mouseout event to each link, and I don't want code anywhere other than within the class (and the mouseover event creating the class instance).

The code:

TestClass = new Class({
    initialize: function(anchor) {
        this.anchor = $(anchor);
        if(!this.anchor) return;

        if(!window.zzz) window.zzz = 0;
        this.id = ++window.zzz;

        this.anchor.addEvent('mouseout', function() {
            // i need to get a reference to this function
            this.hide();
        }.bind(this));

        this.show();

    },
    show: function() {
        // TODO: cool web 2.0 stuff here!
    },
    hide: function() {
        alert(this.id);

        //this.removeEvent('mouseout', ?);  // need reference to the function to remove

        /*** this works, but what if there are unrelated mouseout events? and the class instance still exists! ***/
        //this.anchor.removeEvents('mouseout');

        //delete(this);  // does not work !
        //this = null; // invalid assignment!
        //this = undefined; // invalid assignment!

    }
});

What currently happens with the above code:

  • 1st time out: alerts 1
  • 2nd time out: alerts 1, 2
  • 3rd time out: alerts 1, 2, 3
  • etc

Desired behavior:

  • 1st time out: alerts 1
  • 2nd time out: alerts 2
  • 3rd time out: alerts 3
  • etc

The problem is, each time I mouse over the link, I'm creating a new class instance and appending a new mouseout event for that instance. The class instance also remains in memory indefinitely.

On mouseout I need to remove the mouseout event and destroy the class instance, so on subsequent mouseovers we are starting fresh.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about class