刚开始使用 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
});
谢谢。