<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-tap,但它似乎不起作用! 我认为我使用了错误的语法。 另外,如果我们可以简单地使用预定义的监听器(例如 on-click 和 on-tap),为什么还要使用监听器呢? 我真的很感激任何类型的帮助!
最佳答案
编辑:我帮助更新了 Polymer 的文档。现在已经非常清楚和详细了。 https://www.polymer-project.org/2.0/docs/devguide/events#imperative-listeners只要读一下就可以了。 TL;DR:Polymer 2.0 中不再有监听器对象,但有一种新方法可以实现它。
<小时/>您可以简单地在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
关于 polymer 2.0 : listeners not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43741483/