mitch
mitch

Reputation: 995

Call controller function from XML binding expression

Using OpenUI5/SAPUI5, per documentation on XML Binding Expressions, we have the ability to execute a function from the view.

new sap.m.CheckBox({
    selected: "{= checkSelectedItems(${odata>CustomerId}) }"
})

In my controller behind the view:

checkSelectedItems: function(sCustomerId) {
    return true;
}

In my view, I get the generic error as if it cannot find my function:

Uncaught TypeError: Cannot read property 'apply' of undefined

I've tried calling the function in several ways:

{= .checkSelectedItems() }
{= my.namespace.checkSelectedItems() }

I even tried adding a function in a script tag in my index page to see if it only has access to global functions, but I wasn't able to trigger that either. Suggestions? Am I misinterpreting the documentation?

Please see the JS Bin here : http://jsbin.com/sosotacihi/edit?html,output. I've commented out the CheckBox that has the issue, but if you put it in, you'll see the error.

Upvotes: 8

Views: 8326

Answers (3)

Boghyon Hoffmann
Boghyon Hoffmann

Reputation: 18074

To reuse a controller function in an expression binding, the complex binding syntax works there as well:

selected="{= ${parts: [{path: 'myModel>property'}], formatter: '.myMethodInController'} === 'foo'}"

Currently, it only works when parts:[{path: ...}] is included. But of course, just because it works, doesn't mean we should use it. As you can see, such an expression binding can become quickly unreadable.
UI5 suggests to stick with a formatter function if the expression binding gets hard to read.

We recommend to use formatter functions instead of very complex and hard-to-read expressions.

Check out this documentation.


The syntax someFn(...) in an expression binding works only if someFn is one of the global symbols, such as Math.max(...) or isNaN(...).

Upvotes: 3

Vijayendra Gade
Vijayendra Gade

Reputation: 79

You need to use formatter to call methods of controller from an XML View.

 new sap.m.CheckBox({
     selected: "{parts:['odata>CustomerId'], formatter:'.checkSelectedItems'}"
 });

This can be applied to any event triggering attribute. The generic way to mentioned this is:

{parts:['<parameter1>', '<parameter2>', ...], formatter:'.<methodInController>'}

Upvotes: 3

Sarath Chandra
Sarath Chandra

Reputation: 189

UI5 Suggests to use Expression Binding instead of formatter functions. The Expression binding is mainly for XML views not for JS views.

Upvotes: -1

Related Questions