刚开始使用Web组件(香草),我希望用户能够以编程方式对组件执行操作(例如,“向左滑动组件”)。
我在想(如果有更好的方法,请纠正我)在组件上调度/触发事件,并使组件侦听这些事件。
<custom-element>
// ...
</custom-element>
var customElement = document.querySelector('.custom-element');
customElement.dispatchEvent(new Event('slideLeft'));
然后,在组件中,我需要能够侦听此消息。但是,我不知道如何在<custom-element>
此处访问该元素。
// Gets a handle to this import doc.
var importDoc = document.currentScript.ownerDocument;
// Creates an object based in the HTML Element prototype.
var element = Object.create(HTMLElement.prototype);
// Fires when an instance of the element is created.
element.createdCallback = function () {
// Create a shadow root.
var shadow = this.createShadowRoot();
// Get a reference to the template.
var template = importDoc.querySelector('#custom-element-tpl');
// Append a deep clone of the template into the shadow.
shadow.appendChild(template.content.cloneNode(true));
};
document.registerElement('custom-element', {
prototype: element
});
谢谢。
好的,当我想到这一点时,这很明显,但这里留作参考:
您可以使用..this
内部的上下文来访问当前元素,createdCallback
这createShadowRoot
就是所谓的。
// Fires when an instance of the element is created.
element.createdCallback = function () {
// this = <custom-element></custom-element>
this.addEventListener(...);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句