Javascript 将事件绑定到web组件中的模板文本最方便的方法是什么?
我最近一直在研究web组件,angular/react中遗漏了一件事,那就是将方法自动绑定到类的这个范围。我想这叫做声明性的。在vanilla JS中是否有类似的行为Javascript 将事件绑定到web组件中的模板文本最方便的方法是什么?,javascript,ecmascript-6,web-component,Javascript,Ecmascript 6,Web Component,我最近一直在研究web组件,angular/react中遗漏了一件事,那就是将方法自动绑定到类的这个范围。我想这叫做声明性的。在vanilla JS中是否有类似的行为 export class QuickMenuCmp extends HTMLElement { constructor() { super(); } connectedCallback() { this.innerHTML = this.template;
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中绑定它。您需要将其绑定到函数中,或者通过使用arrow函数对其赋值来使用父级的作用域 试试这个:
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);