Search code examples
titaniumcommonjs

Ti.Include to CommonJS for a beginner


So now that Ti.include is deprecated, I am forced to face the fact that I do not know the correct way to handle commonJS and require.

I have read and re-read many of the posts on SO and elsewhere but still cannot make sense of the syntax. I suspect it is because my original code is somewhat hackish to begin with.

Can anybody help by looking at the small code below and helping me translate it into commonJS?

In the document that contains the current Ti.Include I need to get to the variables dp and 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;
}

Thank you all.


Solution

  • something like this will do.

    Create a file named dpAndFfModule.js and place under the lib folder inside your project.

    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;
    };
    

    now inside .js files you need to require the module like this:

    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.