using export in alloy controller versus attaching functions directly to the '$' scope

262 views Asked by At

here is the code of an alloy controller written in two different ways. Although the both work the same, Which one might be best practice?

example 1 of controller.js:

var currentState = true;
$.getState = function(){
    return currentState;
}

example 2 of controller.js:

var currentState = true;
exports.getState = function(){
    return currentState;
}
2

There are 2 answers

0
Kip Diskin On

Titanium is based on the CommonJS framework. The exports variable is a special variable used typically to expose a public API in a class object. So when you want to expose a method of doSomething() on the MyModule.js class you would use the exports variable like this:

exports.doSomething() = function(args) {
  //Some really cool method here
};

Then reference that class using

var myModule = require('MyModule');
myModule.doSomething();

However when referencing a view object the typical way to reference the is using the $. shortcut. You can see they prefer that method in the official documentation.

http://docs.appcelerator.com/platform/latest/#!/guide/Alloy_XML_Markup

0
KtorZ On

The $ variable holds a reference to your controller instance. It also contains some references to all indexed views (understand, views for which you supplied an index in you xml markup).

Both ways are strictly equivalent as, during the compilation, Alloy will merge the content of the exports with your controller referenced in $. Adding them directly to the instance won't change a thing.

Neverthless, developers are used to see the public API as the set of functions exported via the special variable exports; Thus, I will recommend to keep using it in a clean and clear way (for instance, defining your functions in your module scope, and only expose them at the end or beginning of your controller).

function myFunction1 () { }
function myFunction2 () { }
function myFunction3 () { }


exports.myFunction1 = myFunction1;
exports.myFunction3 = myFunction3;

Thereby, your API is quite clear for people diving into your source code. (A readMe file is also highly recommended :) ).