刚开始使用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
});谢谢。
发布于 2014-08-24 00:33:48
好吧,当我想到这件事的时候,这是很明显的,但我离开这里,以供参考:
可以使用this上下文访问createdCallback中的当前元素。这就是调用createShadowRoot的原因。
// Fires when an instance of the element is created.
element.createdCallback = function () {
// this = <custom-element></custom-element>
this.addEventListener(...);
});https://stackoverflow.com/questions/25467372
复制相似问题