how to update global variable in titanium?

丶灬走出姿态 提交于 2019-12-12 02:37:44

问题


i'm having some problem in updating my array which is global by the way.

here is my code:

Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];

thats my global array which i can access data from it from anywhere in the application.

the problem comes when i want to update the array like:

for(var q=0; q<Ti.App.dinercolor.length; q++){Ti.App.dinercolor[q] = '#dccdc0';}    

so, the array i was expecting after the operation thats done is something like this:

Ti.App.dinercolor=["#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0","#dccdc0"];

but somehow i'm getting the same array with out updating,

Ti.App.dinercolor=["#FF5A00","#007EFF","#dccdc0","#C2FF95","#A700FD","#dccdc0","#dccdc0","#5F9EA0","#dccdc0","#dccdc0","#22A000","#DCCDC0","#dccdc0","#FF003C","#dccdc0","#FF003C","#dccdc0","#22A000","#dccdc0","#FFF191"];

please help me out, i have no idea what i'm doing wrong here,

Thank you,,


回答1:


Your code is correct, but you shouldn't extend the Ti object as unexpected things like this will happen. Create your own object and it will work.

myObj = {};
myObj.dinercolor = [];

And so on.

It is recommended you keep your app in a single context so you will be able to access the object from anywhere. Check out the forging titanium video series for some best practices.




回答2:


I agree with Jeff, however if you want the above approach to work you will need to update the whole array, you cannot just update elements.

So read the array out into a new variable, update the specific elements and then set the property again




回答3:


In App.js:

Ti.App.my_variable = 0;

In some_other_page.js:

Ti.App.my_variable = 101;

In yet_another_page.js:

alert( Ti.App.my_variable );

This will alert 101 !!



来源:https://stackoverflow.com/questions/7552752/how-to-update-global-variable-in-titanium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!