Ti.Include到CommonJS的初学者

时间:2015-01-24 18:52:09

标签: titanium commonjs

所以现在Ti.include已被弃用,我不得不面对这样一个事实:我不知道处理commonJS和require的正确方法。

我已阅读并重读了SO和其他地方的许多帖子,但仍然无法理解语法。我怀疑这是因为我的原始代码开始时有点蠢。

有人可以通过查看下面的小代码帮助我将其翻译成commonJS来帮助吗?

在包含当前Ti.Include的文档中,我需要获取变量dp和ff。

var dp = "";
if (Titanium.Platform.Android) {
    dp = (Ti.Platform.displayCaps.dpi / 160);
} else {
    dp = 1;
}

var version = Titanium.Platform.version.split(".");
version = version[0];

if (Titanium.Platform.displayCaps.platformWidth == '320') {
    ff = 0;
} else if (Titanium.Platform.displayCaps.platformWidth == '768') {
    ff = 3;
} else {
    ff = 1;
}

谢谢大家。

1 个答案:

答案 0 :(得分:0)

这样的事情会发生。

创建一个名为dpAndFfModule.js的文件并放在项目内的lib文件夹下。

exports.getDp = function () {
    var dp = "";
    if (Titanium.Platform.Android) {
        dp = (Ti.Platform.displayCaps.dpi / 160);
    } else {
        dp = 1;
    }
    return dp;
};

exports.getFf = function () {
    var version = Titanium.Platform.version.split(".");
    version = version[0];

    var ff;

    if (Titanium.Platform.displayCaps.platformWidth == '320') {
        ff = 0;
    } else if (Titanium.Platform.displayCaps.platformWidth == '768') {
        ff = 3;
    } else {
        ff = 1;
    }

    return ff;
};

现在在.js文件中你需要这样的模块:

var dpAndFf = require('dpAndFfModule'); //you pass the filename (without extention) to require funciton.

dpAndFf.getDp(); // this executes the getDp function and returns your dp.
dpAndFf.getFf(); // same, executes getFf function and returns the result.