6
votes

In the SAPUI5 Developers Guide I found this note on handling events:

Handling Events in XML Views. Event handlers are used as attributes. The attribute name is the event name, such as "press" for a button, and the attribute value as event handler name. The event handler must be defined as a function in the view's controller. To attach an event handler in a XML view, insert the following declaration: ... <Button text="Press Me" press="doSomething"/> ... The method controller.doSomething() is executed when the button is pressed.

In my XML view, I can translate this into:

<Select change="doSomething">

When the value for the select is changed, the controller.selectOnChange function is called, with the «this argument bound to the controller itself». When I bind this event handler in a JavaScript View, however, the «this argument is bound to the select element».

I assume that this translates into the following code for my JavaScript view:

new sap.m.Select({ change : oController.doSomething })

Am I binding the event handler the wrong way?

2

2 Answers

10
votes

In JS views, when you specify a handler like this:

new sap.m.Button({
    text: "Press Me",
    press: oController.myHandler
})

then this is bound to the control itself in the handler.

But there's another way to specify the handler, like this:

new sap.m.Button({
    text: "Press Me",
    press: [oController.myHandler, oController]
})

where the second element in the array becomes what this is bound to.

I've added an example with a JS view and controller to sapui5bin's SinglePageExamples.

3
votes

If you call it through the XML-View or HTML-View the context of this Event-Method is the controller. In JS-View the context is the control itself. That means you have to call it with jQuery.proxy() like this:

new sap.m.Select({ change : jQuery.proxy(oController.doSomething, oController) })

In this way the oController is your method-context. But I think, you can also use the method addEventDelegate(). See SAPUI5-doc for more information: https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.core.Element.html#addEventDelegate