2017-09-30 41 views
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); 

回答

1

我還沒有玩過Web組件,但我認爲問題只是這是如何綁定在JavaScript中。您需要在函數內綁定它,或者通過爲其分配箭頭函數來使用父級範圍。

試試這個:

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); 
相關問題