2

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

3

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(); 
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

2 Comments

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 answer
So very true. This is what happens when you write before morning coffee.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.