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