i have an helper class in javascript and i must use like this
menu
.createMenu("TestMenu", "Description")
.addMenuItem("test", "", true, true, "callServerTrigger",
"testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
.addCloseButton();
but i must use for loop here.
menu
.createMenu("TestMenu", "Description")
for (var i = 0; i < arr.length; i++) {
.addMenuItem(arr[i], "", true, true, "callServerTrigger", "testServerEvent")
}
.addCloseButton();
I tried this but "." gives syntax error. How can i make this ?
2 Answers 2
You could use a variable for keeping the chained object.
var temp = menu.createMenu("TestMenu", "Description");
for (var i = 0; i < arr.length; i++) {
temp = temp.addMenuItem(arr[i], "", true, true, "callServerTrigger", "testServerEvent");
}
temp.addCloseButton();
Or use Array#reduce, where the return value keeps the chained object.
arr.reduce(function (r, a) {
return r.addMenuItem(a, "", true, true, "callServerTrigger", "testServerEvent");
}, menu.createMenu("TestMenu", "Description")).addCloseButton();
answered May 30, 2017 at 8:47
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Also, if you don't have anything in your arr-array. The length will be 0 at the start and that might be causing the error.
answered May 30, 2017 at 8:49
Iiro Alhonen
4301 gold badge7 silver badges24 bronze badges
2 Comments
Halfpint
This would not cause an error as if the array was empty the logic would simply be skipped and the addCloseButton would still be invoked, the issue is that he is trying to call
addMenuItem without any context, see Nina's answerIiro Alhonen
So very true. This is what happens when you write before morning coffee.
lang-js