javascript - Mootools - 如何销毁类实例

标签 javascript class mootools

我想做的是创建一个可以快速附加到链接的类,它将获取并显示所链接文档的缩略图预览。现在,我在这里专注于易用性和可移植性,我想简单地向链接添加鼠标悬停事件,如下所示:

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

我意识到还有其他方法可以解决我的问题,我可能最终不得不这样做,但现在我的目标是如上所述实现这一点。我不想手动向每个链接添加 mouseout 事件,并且除了类内(以及创建类实例的 mouseover 事件)之外,我不想在任何地方添加代码。

代码:

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!

    }
});

上述代码当前发生了什么:

  • 第一次超时:警报 1
  • 第二次超时:警报 1、2
  • 第三次超时:警报 1、2、3
  • 等等

期望的行为:

  • 第一次超时:警报 1
  • 第二次超时:警报 2
  • 第三次超时:警报 3
  • 等等

问题是,每次我将鼠标悬停在链接上时,我都会创建一个新的类实例并为该实例附加一个新的 mouseout 事件。类实例也无限期地保留在内存中。

在鼠标移出时,我需要删除鼠标移出事件并销毁类实例,因此在后续的鼠标悬停中我们将重新开始。

我可以为此创建一个辅助函数,以确保该类只为每个链接创建一次,如下所示:

function TestClassHelper(anchor) {
    anchor = $(anchor);
    if(!anchor) return;

    if(!anchor.retrieve('TestClass')) anchor.store('TestClass', new TestClass(anchor));
    anchor.retrieve('TestClass').show();
}

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

如果有必要的话,我可能最终会以这种方式实现它,但我很好奇如何修复其他方法。

最佳答案

这看起来比应有的复杂得多。但如果您想解决此问题,则需要在某处保存对绑定(bind)函数的引用,然后将其传递给 removeEvent

例如:

// inside initialize
this.boundHandler = function() {
    this.hide();
}.bind(this)
this.anchor.addEvent('mouseout', this.boundHandler);

// inside hide    
this.removeEvent('mouseout', this.boundHandler);

请参阅removeEvent docs有关此问题的示例。

出于性能原因,我也不建议在这里使用事件委托(delegate)。最好的方法是在代码中而不是内联中附加处理程序,并且只执行一次,这样每次用户将鼠标悬停在上面时就不会创建不必要的对象。

关于javascript - Mootools - 如何销毁类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2982730/

相关文章:

javascript - 替代 Javascript 中 if block 中的多个 or 语句

javascript - 使用 Mootools 对表格行进行排序

javascript - 为什么 Extends 必须是 mootools 类定义中的第一个属性?

javascript - 穆工具 |打开/关闭弹出菜单和外部单击事件

class - 如何从 Powershell 类中正确调用使用 Add-Type 添加的类型的静态方法?

c++ - 简单,但找不到 : syntax to work with member variables of STL queues with type class

javascript - 当管理员在前面登录时,如何找到Joomla 3.0中js包含的位置

javascript - JS 幻灯片重叠 CSS 下拉图像菜单

javascript - ReactJs 动态 setState 在 for 循环中不起作用

C++ 对自定义类初始化器的困惑