我正在为 Android 使用 Titanium 编写应用程序。我在一个 JS 文件中有很多代码。我想知道是否有任何功能像 php 的 include 将代码分成多个文件,然后只包含它们。
谢谢
最佳答案
使用 CommonJS/RequireJS 方法,特别是 require
命令。这是在 Titanium 中处理大型系统的(强烈)推荐方法,并且在他们的网站上有详细记录,以及处理特定于 Titanium 的 JavaScript 模块化的许多最佳实践。 Here is the documentation from Titanium on this.
例如,要创建一个封装某种“ View ”的模块,将其放入名为 MyCustomView.js
的文件中,内容如下:
// MyCustomView.js
function MyCustomView(message) {
var self = Ti.UI.createView({
backgroundColor : 'red'
});
var label = Ti.UI.createLabel({
text : message,
top : 15,
.... // Other initialization
});
// ... Other initialization for your custom view, event listeners etc.
return self;
}
module.exports = MyCustomView;
现在你可以很容易地在另一个类中使用这个模块,假设你把它放在你的 /Resources
文件夹中,让我们在 app.js
中加载模块并添加它到主窗口。
// app.js
var MyCustomView = require('MyCustomView');
var myView = new MyCustomView('A message!');
Titanium.UI.currentWindow.add(myView);
您可以使用这种方法制作自定义 View 、可重用代码库以及您想要的任何其他内容。另一个常见的事情是拥有一个具有许多不同辅助函数的 Utility 类:
// Utility.js
exports.cleanString = function(string) {
// Replace evil characters
var ret = string.replace(/[|&;$%@"<>()+,]/g, "");
// replace double single quotes
return ret.replace(/"/g, "''");
}
这个方法可以像这样轻松使用:
// app.js
var Utility = require('Utility.js');
Ti.API.info(Utility.cleanString('He##o W&orld$'));
我使用它的另一个常用方法是实现 Singleton pattern因为每个加载的模块都是它自己的功能上下文,所以如果你愿意,你可以拥有持久的值:
// ManagerSingleton.js
var SpriteManager = {
count : 0
};
exports.addSprite = function() {
SpriteManager.count++;
}
exports.removeSprite = function() {
SpriteManager.count--;
}
您将以与 Utility 相同的方式加载和使用它:
// app.js
var ManagerSingleton = require('ManagerSingleton');
ManagerSingleton.addSprite();
这是一种比使用全局变量更优雅的解决方案。这些方法绝不是完美的,但它们为我节省了很多时间和挫败感,并为我的适用于各种规模和类型的应用程序的 Titanium 代码增加了深度、优雅和可读性。
关于javascript - 清理一大段 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771883/