gpt4 book ai didi

javascript - 将事件绑定(bind)到 Web 组件中的模板文字的最便捷方法是什么?

转载 作者:行者123 更新时间:2023-12-03 03:22:35 24 4
gpt4 key购买 nike

我最近一直在研究 Web 组件,而我在 Angular/React 中错过的一件事是方法自动绑定(bind)到类的 this 范围。我想这就是所谓的声明式。在 vanilla JS 中是否有任何东西可以模拟这种行为?

export class QuickMenuCmp extends HTMLElement {

constructor() {
super();
}

connectedCallback() {
this.innerHTML = this.template;

// The "type a lot way"
document.querySelector('quick-menu-vsc > .navigator')
.addEventListener('click', () => this.toggleNavMenu())

// The "polute the global scope" way
(<any>window).toggleNavMenu = this.toggleNavMenu;

// Or the "alias" method using bling.js
$('quick-menu-vsc > .navigator').on('click', el => this.toggleNavMenu());

// All of them imperative
}

get template() {
return `
<div class="button ${this.isNavMenuVis ? 'active' : ''}"
onclick="toggleNavMenu()" title="Lessons menu">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
`;
}

private toggleNavMenu(){
console.warn('toggleNavMenu');
}

}

// Component
require('./quick-menu.cmp.scss');
window.customElements.define('quick-menu-vsc', QuickMenuCmp);

最佳答案

我还没有使用过 Web 组件,但我认为问题只是如何在 javascript 中绑定(bind)它。您需要在函数内绑定(bind) this 或通过使用箭头函数分配它来使用父级的作用域。

试试这个:

export class QuickMenuCmp extends HTMLElement {

constructor() {
super();
}

connectedCallback = () => {
this.innerHTML = this.template;

// The "type a lot way"
document.querySelector('quick-menu-vsc > .navigator')
.addEventListener('click', () => this.toggleNavMenu())

// The "polute the global scope" way
(<any>window).toggleNavMenu = this.toggleNavMenu;

// Or the "alias" method using bling.js
$('quick-menu-vsc > .navigator').on('click', el => this.toggleNavMenu());

// All of them imperative
}

get template() {
return `
<div class="button ${this.isNavMenuVis ? 'active' : ''}"
onclick="toggleNavMenu()" title="Lessons menu">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
`;
}

private toggleNavMenu = () => {
console.warn('toggleNavMenu');
}

}

// Component
require('./quick-menu.cmp.scss');
window.customElements.define('quick-menu-vsc', QuickMenuCmp);

关于javascript - 将事件绑定(bind)到 Web 组件中的模板文字的最便捷方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com