Reputation: 619
Like the title said, I've got a simple question in the scope of best practis / good coding. In my component, I often need to access elements from the view. So now I'm wondering, if I should use the sap.ui.getCore().byId(ID)
method to get my elemnt or the this.getView().byId(ID)
operator. I thought maybe it's no matter which of the two I choose, but I want to learn more about this whole sapui5 content and maybe there is an answer way to prefer one solution.
EDIT:
Maybe I was not clear enough with my request and now it's corrected wrong. My question is in the scope of a component. So I wanted to know if I should acces my elemnts by the this
operator or by sap.ui.getCore().byId(ID)
. I know what the this operator is and so on, but I don't know, which variant is "clearer":
Upvotes: 2
Views: 8465
Reputation: 1319
Accessing an element from the current view:
this.getView().byId(...)
Accessing elements from another view, which is not part of the current view (it is not a nested view):
sap.ui.getCore().byId(...)
In my opinion: If you have to do the latter one you did something wrong. Usually, to avoid id conflicts, all id's should be prefixed (done automatically unless this is behaviour is overriden). Downside of this is that you usually don't know what the prefix will look like and thus the above statement won't help you much.
Alternatives:
Cross-controller communication could be handled via the SAPUI5 Event Bus. The subscribers then handle the update of the view. Modification of the View should always be handled by the view's controller. So: Controller C1 modifies V1 = ok, C2 modifies V2 ok, C2 modifies V1 -> bad idea.
Use data binding. A lot of people sometimes seem to forget that it cannot only be used to bind values but also sth like below. The example below can be adapted to a lot of different problems:
// anti-pattern - you will have to do this for all input fields
// which becomes very unhandy very quick.
this.getView().byId("myInput").setEnabled(false).
This is actually a bad approach. Way better would be to have a model - let's say "pageState" and bind the elements "enabled"-property to this model. E.g. like this:
<Input enabled="{pageState>/inputFieldsEnabled} ... />
and then in the controller
this.getModel("pageState").setProperty("/inputFieldsEnabled", false);
Upvotes: 7
Reputation: 1742
var el = sap.ui.getCore().byId("btn");
el = this.getView().byId("btn");
Both of the above can return control with specified ID, but when you try to access control with getCore()
it has to look for that particular element in entire Core framework in current window, whereas with this.getView()
it has to only look within current view.
So from performance point of view using this.getView()
would be good choice.
getCore()
should be used when you have something that is not accessible via this.getView()
in current context.
for e.g., accessing Input
control in currently opened fragment.
Upvotes: 2