Correct event binding in JavaScript view? Different this binding with XML views
sapui5
Solution
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`.
Problem
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?