鉴于下面的对象,this.delegateBind = this.delegate.bind(this)
是处理事件监听器的唯一选择吗?我已经阅读了其他相关的问题,这些问题表明这是正确的模式,但它似乎不够优雅......是否有一种更简洁的模式我不知道?
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
}
}
}