Correct event binding in JavaScript view? This binding differs with XML views

In the SAPUI5 Developer's Guide, I found this event handling note:

Event handling in XML views. Event handlers are used as attributes. An attribute name is an event name, such as a β€œclick” for a button, and an attribute value as the name of an event handler. An event handler must be defined as a function in the view controller. To attach an event handler in the XML view, insert the following declaration: ... <Button text="Press Me" press="doSomething"/> ... The controller.doSomething() method is executed when the button is clicked,

In my XML view, I can translate this to:

 <Select change="doSomething"> 

When the value for the selection changes, the controller.selectOnChange function is called with "this argument associated with the controller itself." However, when I bind this event handler in a JavaScript view, "this argument is bound to a select item."

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

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

Am I binding the event handler incorrectly?

+6
source share
2 answers

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

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

then this is associated with the control itself in the handler.

But there is another way to specify a 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 associated with.

I added an example with JS representation and controller in sapui5bin SinglePageExamples .

+8
source

If you call it through an XML view or an HTML view, the context of this Event method is the controller. In JS-View, the context is the control itself. This means that you must call it using jQuery.proxy() as follows:

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

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

+3
source

All Articles