如何采用OOP方式在类构造函数的addEventListener中传递参数
类构造函数中addEventListener传参的解决方法
你当前使用bind传参的思路本身是可行的,只需修正两个问题即可正常运行:
Function.prototype.bind传入的自定义参数,会优先于事件对象传入处理函数,你当前fadeRow的参数顺序写反了- 代码中
opacitybutton属于笔误,应该替换为你之前声明的button变量
方案1:修正bind写法
调整fadeRow的参数顺序即可,修正后的完整代码如下:
class Todo { #card = document.querySelector('.card'); #expandButton = document.querySelector('.sidebar__expand'); #sidebar = document.querySelector('.sidebar') constructor() { this.#card.addEventListener('mouseover',this.fadeRow.bind(this, 0.5)) this.#card.addEventListener('mouseout',this.fadeRow.bind(this, 1)) this.#expandButton.addEventListener('click', this.expandSidebar.bind(this)) } // 调整参数顺序:bind传的自定义参数在前,事件对象e在后 fadeRow(opacity, e) { if(e.target.closest('.card__delete')) { const button = e.target.closest('.card__delete'); console.log(button); // 修正笔误:opacitybutton 改为 button const siblings = button.closest('.card').querySelectorAll('.card__delete'); siblings.forEach(sib => sib.style.opacity = '1'); button.style.opacity = opacity; } } }
方案2:用箭头函数包裹传参
如果不想调整原有函数的参数顺序,可以直接用箭头函数包裹处理逻辑,写法更直观:
constructor() { // 箭头函数保留了this指向,直接按你需要的顺序传参即可 this.#card.addEventListener('mouseover', (e) => this.fadeRow(e, 0.5)) this.#card.addEventListener('mouseout', (e) => this.fadeRow(e, 1)) this.#expandButton.addEventListener('click', (e) => this.expandSidebar(e)) } // 原有参数顺序不需要修改 fadeRow(e, opacity) { // 原有逻辑不变,修正opacitybutton笔误即可 }
注意事项
如果后续需要调用removeEventListener移除监听事件,不要直接使用匿名箭头函数或临时bind生成的函数,建议将绑定后的处理函数存储为类的实例属性,方便后续引用移除:
constructor() { // 先把绑定后的函数存到实例属性上 this.handleFadeIn = this.fadeRow.bind(this, 0.5) this.#card.addEventListener('mouseover', this.handleFadeIn) } // 移除时直接引用存储的函数即可 removeFadeListener() { this.#card.removeEventListener('mouseover', this.handleFadeIn) }
内容的提问来源于stack exchange,提问作者Kay
相关产品推荐
相关产品推荐

