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

I'm trying to remove event handler with removeEventDelegate but it doesn't work

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

这是我添加 eventListener 的方式:

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

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

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

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

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

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
})

方法 removeEventDelegate 等待调用 addEventDelegate 时传递的相同 object 因为元素查找对象 reference 删除它时(参见 source code)。功能新不新都无所谓

下面是一个演示删除事件委托的示例:

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。例如,参见 whosebug.com/a/56852018.