首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从自身访问Web组件元素

从自身访问Web组件元素
EN

Stack Overflow用户
提问于 2014-08-23 23:51:31
回答 1查看 240关注 0票数 0

刚开始使用Web组件(香草),我希望用户能够以编程方式对组件执行操作(例如,“幻灯片组件左”)。

我正在考虑(如果有更好的方法的话)来在组件上分派/触发事件,并让组件侦听这些事件。

代码语言:javascript
复制
<custom-element>
    // ...
</custom-element>

var customElement = document.querySelector('.custom-element');
customElement.dispatchEvent(new Event('slideLeft'));

然后在组件中,我需要能够听这个..但是我不知道如何在这里访问<custom-element>元素。

代码语言:javascript
复制
// 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
});

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-24 00:33:48

好吧,当我想到这件事的时候,这是很明显的,但我离开这里,以供参考:

可以使用this上下文访问createdCallback中的当前元素。这就是调用createShadowRoot的原因。

代码语言:javascript
复制
// Fires when an instance of the element is created.
element.createdCallback = function () {
    // this = <custom-element></custom-element>
    this.addEventListener(...);
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25467372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档