jeudi 8 février 2018

Is assigning a bound function to a var really the only option?

Given the Object below, is this.delegateBind = this.delegate.bind(this) my only option when dealing with event listeners and this? I've read other related questions that suggest this is the proper pattern, but it seems inelegant... Is there a more succinct pattern I'm missing?

const foo = {
  init: function(btn){
    this.btn = btn
    this.delegateBind = this.delegate.bind(this)

    btn.addEventListener('click', this.toggle.bind(this))
  },
  toggle: function(e){
    console.log('do stuff')

    if(something){
      document.body.addEventListener('click', this.delegateBind)
    }else{
      document.body.removeEventListener('click', this.delegateBind)
    }
  },
  delegate: function(e){
    switch(true){
      case e.target.matches('.btn-close'):
        this.btn.click()
        break
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire