【问题标题】:I'm trying to remove event handler with removeEventDelegate but it doesn't work我正在尝试使用 removeEventDelegate 删除事件处理程序,但它不起作用
【发布时间】:2025-12-20 17:00:07
【问题描述】:

我正在尝试使用removeEventDelegate 方法删除事件处理程序,但它不起作用。

这就是我添加 eventListener 的方式:

appointment.addEventDelegate({
    ondragstart: this.myFunction.bind(this, temp)
})

这就是我尝试删除它的方式,但它不起作用:

appointment.removeEventDelegate({
    ondragstart: this.myFunction.bind(this, temp)
})

【问题讨论】:

    标签: javascript sapui5 event-delegation removeeventlistener


    【解决方案1】:

    方法removeEventDelegate 等待调用addEventDelegate 时传递的相同对象,因为元素在删除它时会查找对象reference(请参阅@987654321 @)。功能是否新无关紧要。

    以下是演示移除事件委托的示例:

    sap.ui.getCore().attachInit(() => sap.ui.require([ "sap/m/ToggleButton" ], ToggleButton => {
      const myDelegate = { // same reference for removing and adding delegate
        onmouseover: () => console.log("mouse hovering"), // e.g.
      };
    
      const myBtn = new ToggleButton({
        text: "Delegate",
        press: () => !myBtn.getPressed()
          ? myBtn.removeEventDelegate(myDelegate) && console.clear()
          : myBtn.addEventDelegate(myDelegate, this), // `this` should be the controller instance in your case. 
      }).placeAt("content");
    
    }));
    console.clear();
    <script id="sap-ui-bootstrap" src="https://ui5.sap.com/resources/sap-ui-core.js"
      data-sap-ui-libs="sap.m"
      data-sap-ui-async="true"
      data-sap-ui-theme="sap_fiori_3"
      data-sap-ui-compatversion="edge"
    ></script>
    <body id="content" class="sapUiBody"></body>

    因此,您必须将委托对象保存在某处,以便稍后将其传递给removeEventDelegate。例如,请参阅*.com/a/56852018

    【讨论】:

      【解决方案2】:

      function 上使用bind每次都会创建该函数的新实例。如果您没有reference(指向该实例的变量/属性),则在用作侦听器时无法将其删除。

      所以要么将该实例分配给一个新变量,要么只用绑定的实例覆盖函数,以防您不想要/不需要任何未绑定的实例:

      this.myFunction = this.myFunction.bind(this, temp)
      // or
      this.myBoundFunction = this.myFunction.bind(this, temp);
      
      appointment.addEventDelegate({
          ondragstart: this.myFunction
      })
      
      
      appointment.removeEventDelegate({
          ondragstart: this.myFunction
      })
      

      【讨论】:

      • 问题是这个处理程序被附加到几个控件并且它们都有不同的温度值。所以我不能存储所有的参考资料。任何其他想法,是否有删除所有与 odragstart 事件相关的处理程序?
      • 在不了解您的代码和用例的情况下,我无法在此提供建议。我所说的仍然是真实的。也许您可以将绑定的实例推送到 this.myBoundFunctions 数组中并使用索引绑定/取消绑定它们?
      最近更新 更多