与使用$ .each相比,向jQuery类集添加侦听器的效率

ans*_*son 6 javascript optimization jquery jquery-plugins

初始直觉告诉我添加一个监听器,使用bind或简单的事件方法来处理jQuery元素集,例如..

$('.className').click(funcName);

比使用$ .each方法将侦听器逐个添加到同一个集合更合适...

$('.className').each(function(){ $(this).click(funcName); });

但是当谈到插件开发时,你正在处理用户在页面生命周期内,页面加载和页面加载后很长时间内多次调用插件实例的可能性,将处理程序应用于每个元素本身,而不是试图将处理程序抽象为它们的全局类集?

我正在处理的主要问题是"处理事件处理时调用的插件的多个实例的最佳方法是什么?为了减少工作量?" 我知道我们可以绑定和取消绑定,但有更好的方法吗?

编辑

插件构造的部分代码

init : function(){

  this.each(function(opts){

  // adding event handlers here removes
  // the need to worry about multiple instances
  // and duplicate handles over the lifetime of the page

  });

  // adding 'global' handlers here may/may not be more
  // efficient, but adds an issue of multiple instances

  return this;

}
Run Code Online (Sandbox Code Playgroud)

Yus*_*f X 1

您的问题是关于“效率”,我认为这意味着“客户端的速度”。也许任何合理的方法都会对感知性能产生最小的影响,因此我建议您选择最容易维护的编码模式。