Create SAPUI5 control using new Function() and str

2019-09-07 20:14发布

This question is a continuation of this one.

I have a list of SAPUI5 controls in string format and to extract the required control I use:

var sDefaultControlConstructor = "new sap.m.Input()"; 
var sConstructor = "return " + sDefaultControlConstructor;
var oConstructor = new Function(sConstructor);
var oField = oConstructor();

The oField object I get looks like follows in the console:

M.c…s.f {bAllowTextSelection: true, mEventRegistry: Object, sId: "id", mProperties: d, mAggregations: Object…}

The problem is that I cannot get the created object using sap.ui.getCore().byId() function.

I looked for the differences between the object I create and the object which is created "normally"

var oField = new sap.m.Input();

it looks like this:

d {bAllowTextSelection: true, mEventRegistry: Object, sId: "id", mProperties: d, mAggregations: Object…}

Obviously, these two object are different.

The question is how do I create the control of the second format using new Function().

Thank you.

1条回答
爷、活的狠高调
2楼-- · 2019-09-07 20:36

OK, I have found the solution. I was declaring the control wrong - the id to every control is given by user when this control is being created, while when user doesn't give any id to the control, it is given automatically.

So, when I did

var sDefaultControlConstructor = "new sap.m.Input()"; 
var sConstructor = "return " + sDefaultControlConstructor;
var oConstructor = new Function(sConstructor);
var oField = oConstructor();

my control oField was created with automatically generated and assigned id.

And when I give id to this control afterwards -

oField.sId = "someID";

this control cannot be seen by sap.ui.getCore().byId("someID"); (I honestly don't know why. It always return undefined).

To fix the issue, its required to assign control's id during the control's creation:

var oConstructor = new Function("a", "return new sap.m.Input(a)");
var oField = oConstructor({id:'someID'});

OR

var sId = 'someID';
var oConstructor = new Function("a", "return new sap.m.Input(a)");
var oField = oConstructor({id:sId});

HERE is JSBIN example of two above declarations (working and not working ones).

查看更多
登录 后发表回答