我尝试了很多方法,但都没有成功。
我在想这是否不可能?
我知道使用'bind'的“正常”方式,但箭头函数更易读,我更喜欢使用它们。
为了更好地理解我的问题,我编写了这段示例代码,尽可能全面地说明了问题。
为了更好地理解我的问题,我编写了这段示例代码,尽可能全面地说明了问题。
class MyClass_XY {
constructor(zID) {
let ref = document.getElementById(zID);
this.name = zID;
this.Info = ref.querySelector('span');
this._Bt_Plus = ref.querySelector('.plus');
this._bt_Stop = ref.querySelector('.stop');
this.Nbre = 0;
// this.stop = false; // I don't whant this, because this is a small sample code of something more complex
this._Bt_Plus.onclick = e => this._f_Bt_Plus_click(e);
this._bt_Stop.onclick = e => this._f_Bt_Stop_click(e);
/*
this.fct_Ref = null;
this._Bt_Plus.addEventListener('click', this.fct_Ref = this._f_Bt_Plus_click.bind(this) , false );
*/
}
_f_Bt_Plus_click(e) {
e.stopPropagation();
console.log(e.target.innerText);
this.Nbre++,
this.Info.innerText = this.Nbre.toString();
}
_f_Bt_Stop_click(e) {
e.stopPropagation();
// this._Bt_Plus.removeEventListener('click', this.fct_Ref , false ); // is OK, how to deal the other ?
this._Bt_Plus.removeEventListener("click", this._f_Bt_Plus_click, true); // didn't work :/
console.log(this.name, '_Bt_Plus remove onclick ');
}
}
var
Ananas = new MyClass_XY('Pineapple'), // I am a frog
Bananes = new MyClass_XY('Bananas');
<p id='Pineapple'> pineapple <span>0</span>
<button class="plus">+1 pineapple</button>
<button class="stop">stop</button>
</p>
<p id='Bananas'> Bananas <span>0</span>
<button class="plus">+1 Bananas</button>
<button class="stop">stop</button>
</p>
onclick
的问题在于一次只能附加一个监听器,而addEventListener
大多数情况下要好得多。 - CertainPerformance.onclick
还是addEventListener
),则可以改用事件委派 - 向zID
的容器添加单个单击侦听器,从单击元素找到外部ref
,然后使用Map
来获取该ref
的实例化MyClass_XY
。 - CertainPerformance