2017-09-30 5 views
0

저는 최근에 웹 컴포넌트에 대한 작업을 해왔고 각도/반응에서 빠뜨린 것은 하나의 메소드를 자동으로 바인딩하여 this 클래스의 범위입니다. 선언이라고 부르는 것 같아요. 바닐라 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); 

답변

1

아직 웹 구성 요소를 사용하지 않았지만이 문제는 자바 스크립트에서 어떻게 바인딩되는지 간단하게 생각합니다. 이 함수를 함수 내에 바인딩하거나 부모 함수의 범위를 화살표 함수로 할당해야합니다.

이 시도 :

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);