【问题标题】:JavaScript Closure - listen event for all elements of a classJavaScript Closure - 监听类的所有元素的事件
【发布时间】:2015-08-07 00:02:03
【问题描述】:

是否可以在 Closure 中将事件绑定到类的所有元素?我知道在 jQuery 中它类似于

$('.my_class').click(...)

Closure 中有类似的东西吗?类似的东西

goog.events.listen('.my_class', ...)

【问题讨论】:

  • 不幸的是,并非如此。 querySelectorAll NodeList 上的正常循环将是最简单的。

标签: javascript dom google-closure google-closure-library


【解决方案1】:

你的意思是像下面这样吗?

参考:http://closure-library.googlecode.com/git-history/docs/namespace_goog_events.html

var source = new goog.events.EventTarget();
  function handleEvent(e) {
    alert('Type: ' + e.type + '; Target: ' + e.target);
  }
  source.listen('foo', handleEvent);
  // Or: goog.events.listen(source, 'foo', handleEvent);
  ...
  source.dispatchEvent('foo');  // will call handleEvent
  ...
  source.unlisten('foo', handleEvent);
  // Or: goog.events.unlisten(source, 'foo', handleEvent);

【讨论】:

    【解决方案2】:

    正如 joeltine 已经提到的,Google Closure Lib 中没有这样的本地方法。您可以使用 G 库: https://github.com/rhysbrettbowen/G-closure#gon-uid

    或者创建另一个原型来提供高级监听方法。这些片段可以服务于基本元素:

    yourapp.prototype.listenAll = function(nodes, callbackFunc) {
      for (var i = 0; i < nodes.length; i++) {
        goog.events.listen(nodes[i], type, callbackFunc);
      }
    };
    

    【讨论】:

    猜你喜欢
    • 2015-02-03
    • 2021-06-11
    • 2014-02-24
    • 2021-03-17
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2022-01-17
    • 2017-04-16
    相关资源
    最近更新 更多