我构建了一个 javascript 库,它将指针事件监听器附加到 DOM 元素 ( here )。今天,我在 Polymer 1.9 Web 组件中使用它来包装它,使用 PEP在 Firefox 上填充指针事件,效果很好:
<link rel="import" href="./pepjs-import.html">
<link rel="import" href="./myscriptjs-import.html">
<dom-module id="myscript-common-element">
<template>
<style></style>
<div id="editorDomElement" class="ms-editor"></div>
</template>
<script>
Polymer({
is: 'myscript-common-element',
properties: {},
attached: function () {
this.editorDomElement = this.querySelector('#editorDomElement');
// Attach an editor to the DOM element and listen pointer events
this.editor = MyScript.register(this.editorDomElement, this.buildConfiguration(), this.buildCustomStyle());
}
}
);
</script>
我只是在注册下执行 elementDomElement.addEventListener('pointerdown', (e) => {//Some code });
,没什么特别的。
迁移到 Polymer 2 后,我得到了类似的结果:
<dom-module id="myscript-common-element">
<template>
<style></style>
<div id="editorDomElement" class="ms-editor"></div>
</template>
<script>
class MyScriptCommonElement extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], Polymer.Element) {
static get is() {
return 'myscript-common-element'
}
connectedCallback() {
super.connectedCallback();
this.editorDomElement = this.shadowRoot.querySelector('#editorDomElement');
this.editor = MyScript.register(this.editorDomElement, this._buildConfiguration(), this._buildCustomStyle());
}
}
customElements.define(MyScriptCommonElement.is, MyScriptCommonElement);
</script>
指针事件在 Chrome 和 Edge 下可以正确处理,但在 Firefox 中,事件卡在 ShadowRoot 上。如果我正在收听 this
,我可以处理它们,例如ShadowRoot,但不在 editorDomElement
上。
我做错了什么,还是 Firefox 上的 Polymer 2 事件转发存在问题?有没有解决方案或解决方法可以使其发挥作用? 谢谢
最佳答案
在 Polymer 2.0 中,事件
将在 ShadowRoot 边界上停止并消失在烟雾中。
如果你想让事件泄漏到shadowRoots之外,你需要在dispatchEvent函数中传递composed属性:
this.dispatchEvent('my-event', { bubbles: true, composed: true });
在这里阅读更多信息:Fire Custom Events (polymer-project.org)
关于javascript - 如何使用 Polymer 2 在 Firefox 上的 Web 组件中捕获指针事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44850306/