Search This Blog

Wednesday, August 29, 2012

Js Modules with Titanium Appcelerator Framework

Here are the two ways you could currently use JS modules within the Titanium Mobile Framework from appcelerator:

1. Function Module

Assume you have a FunctionModule.js with the following content:

// an internal variable, which is only accesible within the module
var internalMsg = "Only visible within the module";

// an exported function, which this module offers
exports.hello = function(msg) {
alert('your message: ' + msg + ' internal message: ' + internalMsg);
}


you could use you module like this:

// reference the module
var fmo = require('/ui/common/FunctionModule');

// call the exported function
fmo.hello('External Message');










// no access from the outside to the internal variable
alert('interal var from module: ' + fmo.internalMsg)




2. Object Module

Assume you have a ObjectModule.js with the following content:


// constructor of your object
function Sample(name) {
   this.name = name;
}
// function, which alerts the current name
Sample.prototype.showName = function() {
alert('Name: ' + this.name);
}
// function, which sets the name
Sample.prototype.setName = function(name) {
this.name = name;
}
// you just export your Object and override the methods as prototypes
module.exports = Sample;


you could use you module like this:


// reference the module
var SampleModule = require('/ui/common/ObjectModule');
// Create a sample Object
var sam = new SampleModule('Fred');
// call a Method
sam.showName();

// change the internal name
sam.setName('Hugo');
sam.showName();













No comments:

Post a Comment