如何使用命名函数调用附加/分离事件?

How can I call the attach / detach events with a named function?

我有一个函数需要附加和分离处理程序到 OData 模型的事件 "requestCompleted" 以从 header 获取 URL 以便下载数据作为 Excel 文件。

onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadODataAsExcel);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/ZService/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
},

我正在尝试事后分离事件,以防止事件滚雪球,每次单击下载按钮时都会导致文件下载 n+1 次。


更新:这是我最终得到的代码

onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadOdataAsExcel, this);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/Z_SERVICE/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
    var model = this.getView().getModel();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
}

分离需要在函数内进行,否则侦听器将在 requestCompleted 事件触发之前分离。

试试这个:

model.attachRequestCompleted(this.downloadOdataAsExcel, this);

然后尝试访问 'evt' 对象。

可以通过将相同的参数列表传递给方法来附加和分离事件处理程序。例如:

myModel.attachRequesCompleted(this.onRequestCompleted/*NO .bind*/, this); // Pass the oListener (this) as an argument instead
myModel.detachRequestCompleted(this.onRequestCompleted/*NO .bind*/, this); // Same list of arguments

“相同的参数列表”,我的意思是:

  • 不要不要直接传递匿名函数作为事件处理程序。稍后尝试分离它时无法引用它。

  • 不要不要直接使用.bind传递函数因为.bind会创建一个new 功能,这再次使它无法分离。

  • 传递相同的 oListener 参考。来自 API 描述:

    The passed function and listener object must match the ones used for event registration. (Source)

相同的 也适用于 ManagedObject 生成的所有 attach* / detach* 方法。

在您的情况下,处理程序无法分离,因为侦听器对象在附加处理程序时是 undefined 而不是 this


或者,也可以使用 attachEventOnce

myModel.attachEventOnce("requestCompleted", this.onRequestCompleted, this);

调用处理程序后,它会自动分离。