0
我最近一直在web組件上工作,有一件事是我從角度/反應中錯過的方法的自動綁定到this
範圍的類。我想這就是所謂的聲明。有沒有什麼能夠模仿香草JS中的這種行爲?將事件綁定到Web組件中的模板文字最方便的方法是什麼?
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);