0

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

谢谢。

4

1 回答 1

1

好的,当我想到它时,这有点明显,但留在这里供参考:

您可以使用.. 中的this上下文访问当前元素,这就是调用的内容。createdCallbackcreateShadowRoot

// Fires when an instance of the element is created.
element.createdCallback = function () {
    // this = <custom-element></custom-element>
    this.addEventListener(...);
});
于 2014-08-24T00:33:48.093 回答