4
<dom-module id="polymer-starterkit-app">
  <template>
    <style>
        :host {
        display: block;
        }
        #box{
            width: 200px;
            height: 100px;
            border: 1px solid #000;
        }  
    </style>
    <h2>Hello, [[prop1]]!</h2>
    <paper-input label="hello">

    </paper-input>

    <div id="box" on-click="boxTap"></div>
  </template>

  <script>
    /** @polymerElement */
    class PolymerStarterkitApp extends Polymer.Element {
      static get is() { return 'polymer-starterkit-app'; }
      static get properties() {
        return {
          prop1: {
            type: String,
            value: 'polymer-starterkit-app'
          },
          listeners:{
            'click':'regular'
          },
          regular:function(){
              console.log('regular')
          }    

        };


      }
     boxTap(){
        console.log('boxTap')
     }

    }

    window.customElements.define(PolymerStarterkitApp.is, PolymerStarterkitApp);
  </script>
</dom-module>

如上面的代码所示,我试图用类框在我的 div 上定义一个简单的监听器,但它似乎不起作用!我想我使用了错误的语法。另外,如果我们可以简单地使用预定义的侦听器,例如 on-click 和 on-tap,为什么还要使用侦听器呢?我真的很感激任何类型的帮助!

4

2 回答 2

6

编辑:我帮助更新了 Polymer 的文档。现在非常清晰和详细。https://www.polymer-project.org/2.0/docs/devguide/events#imperative-listeners只需阅读即可。TL;DR:在 Polymer 2.0 中不再使用 listeners 对象,但有一种新方法可以做到这一点。


您可以简单地将它们设置在ready(). .bind()在这种情况下不需要使用,因为this它将是回调中的自定义元素,因为它是事件的当前目标。

ready () {
  super.ready()
  this.addEventListener('my-event', this._onMyEvent)
}

_onMyEvent (event) { /* ... */ }

如果您需要侦听不是您的自定义元素本身(例如window)的事件,请按照 Polymer 文档中显示的方式进行操作:

constructor() {
  super();
  this._boundListener = this._myLocationListener.bind(this);
}

connectedCallback() {
  super.connectedCallback();
  window.addEventListener('hashchange', this._boundListener);
}

disconnectedCallback() {
  super.disconnectedCallback();
  window.removeEventListener('hashchange', this._boundListener);
}

资料来源:https ://www.polymer-project.org/2.0/docs/devguide/events#imperative-listeners

于 2017-09-02T10:51:07.373 回答
-1

您必须手动创建侦听器

connectedCallback() {
    super.connectedCallback();
    this.addEventListener('click', this.regular.bind(this));
}

disconnectedCallback() {
    super.disconnetedCallback();
    this.removeEventListener('click', this.regular);
}

regular() {
    console.log('hello');
}

但是,要将侦听器添加到像 div 这样的元素,您需要添加 Polymer.GestureEventListeners

class PolymerStarterkitApp extends Polymer.GestureEventListeners(Polymer.Element) {

}
于 2017-05-05T00:17:40.373 回答