Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sapui5 - Difference Between this.getView().byId(), this.byId(), and sap.ui.getCore().byId()

Can I know the difference and performance when I use:

const myControl = this.getView().byId("myIDhere");
const myControl = this.byId("myIDhere");
const myControl = sap.ui.getCore().byId("myIDhere");

Which of three is best to use to perform operations on control when I use XML views in UI5 apps?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

About this.getView().byId and this.byId (Recommended)

Take a look at the source code of the this.byId method:

// sap.ui.core.mvc.Controller
Controller.prototype.byId = function(sId) {
  return this.oView ? this.oView.byId(sId) : undefined;
};

As you can see, this.byId is just a shortcut for this.getView().byId. They both can be used to access controls defined in the view. E.g.:

<!-- Given -->
<Panel id="myPanel" />
myControllerMethod() {
  const thatPanel = this.byId("myPanel"); // === this.getView().byId("myPanel")
},

About sap.ui.getCore().byId (Don't use it)

The API sap.ui.getCore().byId(/*...*/) on the other hand, awaits a fully concatenated global ID which is why you cannot simply exchange this.byId with sap.ui.getCore().byId if the target control is a view descendant.

sap.ui.getCore().byId("__xmlview0--myPanel"); // <-- Avoid concatenating ID parts!

Generally, sap.ui.getCore() should be avoided when developing UI5 applications that would be added to Fiori launchpad (FLP). I.e. when instantiating a control in the controller, keep in mind to use the API createId:

new Panel("myPanel");

new Panel(this.createId("myPanel")); // Makes it accessible via this.byId("myPanel")

From the topic "JavaScript Coding Issues" section "Don't create global IDs":

[...] you must not create stable IDs for your controls, fragments, or views in OpenUI5. Doing so might result in duplicate ID errors that will break your app. Especially when running together with other apps, there could be name clashes or other errors.

Use the createId() function of a view or controller instead. This is done automatically in XMLViews and JSONViews. The createId() function adds the View ID as a prefix, thus recursively ensuring uniqueness of the ID.

More about IDs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...