在 php 中,您只需执行以下操作即可轻松添加到全局变量中:
$array = ['pigs','cows'];
for($i = 0 ; $i < count($array); ++$i ){
$GLOBALS[$array[i]] = 'somthing cool';
}
我正在尝试使用 js 实现类似的东西,但不确定是否可能:
var events = [
'AboutView',
'FindView',
];
for( var i = 0 ; i < views.length ; ++i ){
/* where <views[i]> is a globally defined variable the name of the array val */
<views[i]> = require( 'ui/common_new/' + views[i] );
Ti.include( 'events/'+views[i]+'.js' );
}
然后能够像这样访问视图:
var new FindView = new FindView();
在循环外部定义视图数组,然后将每个项附加到其中。喜欢这个:
var views = [];
for( var i = 0 ; i < views.length ; ++i ){
/* where <views[i]> is a globally defined variable the name of the array val */
views[i] = require( 'ui/common_new/' + views[i] );
Ti.include( 'events/'+views[i]+'.js' );
}
或执行 window.variable 以定义任何范围的全局变量
您可以编写一个泛型函数,该函数将在指定的容器中创建视图:
function registerViews(views, container)
{
views.forEach(function(view) {
container[view] = require('ui/common_new/' + view);
Ti.include('events/' + view + '.js');
});
}
var views = [
'AboutView',
'FindView',
];
然后根据需要使用 window
调用它:
registerViews(views, window);
var x = new FindView();
或其他容器:
var test = {};
registerViews(views, test);
var x = new test.FindView();