2010-06-06 47 views
2

我想要做的是创建一个类,我可以快速附加到链接,它将获取并显示链接到文档的缩略图预览。现在,我注重易用性和便携性在这里,我想简单的鼠标悬停事件添加到链接是这样的: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
  • 第二次了:警告1,2
  • 第3次out:alerts 1,2,3
  • etc

期望的行为:

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

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

在mouseout上,我需要删除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>

我可能最终实现它这样如果我必须,但我很好奇如何解决其他方法。

回答

3

这看起来比应该复杂得多。但是如果你想解决这个问题,你需要在某处保存一个对绑定函数的引用,然后传递给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

由于性能方面的原因,我不会在此推荐活动委托。最好的方法是用代码而不是内联方式附加处理程序,只做一次,因此每次用户鼠标悬停时都不会创建不必要的对象。

+0

感谢您的回复。这将删除mouseout事件,但是当您指出我仍然创建了不必要的额外对象时,所以我想我将不得不按照您的建议来简化它。我想我会创建一个单一的全局实例来处理所有链接,并执行像这样的 Rob 2010-06-07 14:11:58

+0

@Rob有一个单一的全局共享实例似乎是一个很好的选择,因为这里的每个链接都没有对象特定的状态。 – Anurag 2010-06-08 18:47:28