我正在学习使用Titanium制作iPhone/Android应用程序。我正在使用Alloy MVC框架。除了HTML中的简单脚本来访问DOM或类似的东西外,我从来没有使用过JavaScript,所以我从来不需要构造代码。在Titanium项目中使用Alloy和CommonJS组织JS代码
现在,与钛,我必须使用大量的JS代码,我正在寻找方法来构建我的代码。基本上我发现了3种方法:函数内部的原型,名称空间和函数。
每个简单的例子:
原型:
NavigationController = function() {
this.windowStack = [];
};
NavigationController.prototype.open = function(windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
if (that.windowStack.length > 1)
{
that.windowStack.pop();
}
});
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
this.navGroup.open(windowToOpen);
}
};
NavigationController.prototype.back = function(w) {
//store a copy of all the current windows on the stack
if(Ti.Platform.osname === 'android') {
w.close();
} else {
this.navGroup.close(w);
}
};
module.exports = NavigationController;
使用它作为:
var NavigationController = require('navigator');
var navController = new NavigationController();
命名空间(或者我觉得是这样的事情,怎么使用我= {}):
exports.createNavigatorGroup = function() {
var me = {};
if (OS_IOS) {
var navGroup = Titanium.UI.iPhone.createNavigationGroup();
var winNav = Titanium.UI.createWindow();
winNav.add(navGroup);
me.open = function(win) {
if (!navGroup.window) {
// First time call, add the window to the navigator and open the navigator window
navGroup.window = win;
winNav.open();
} else {
// All other calls, open the window through the navigator
navGroup.open(win);
}
};
me.setRightButton = function(win, button) {
win.setRightNavButton(button);
};
me.close = function(win) {
if (navGroup.window) {
// Close the window on this nav
navGroup.close(win);
}
};
};
return me;
};
使用它作为:
var ui = require('navigation');
var nav = ui.createNavigatorGroup();
函数内部功能:
function foobar(){
this.foo = function(){
console.log('Hello foo');
}
this.bar = function(){
console.log('Hello bar');
}
}
// expose foobar to other modules
exports.foobar = foobar;
使用它作为:
var foobar = require('foobar').foobar
var test = new foobar();
test.bar(); // 'Hello bar'
现在我的问题是:哪个是更好的保持代码清洁和清晰?看起来原型很容易读懂/保守。命名空间使我困惑一些,但只需要执行初始函数以“可用”(在声明它时不使用新的,我想是因为它返回对象?命名空间?“我”)。最后,函数内部的函数与最后一个相似,所以我不清楚它们的区别,但是仅导出主函数并且可以在后面使用所有内部函数。
也许最后两种可能性是相同的,我搞乱了概念。
请记住,我正在寻找一种构建代码的好方法,并且可以为其他模块提供功能,也可以在自己的模块中使用这些功能。
我很感激任何澄清。
嗨,@马丁。感谢您的答复。我对你推荐的这个项目做了一点点看法,它似乎使用了“函数内部的函数”方法。正如你所说,最重要的是对选择感到满意。现在我正在使用原型,我觉得很清楚,但会看到是否有更多的意见。 – Eagle