Skip to content

Instantly share code, notes, and snippets.

@tsteur
Created July 15, 2013 22:12
Show Gist options
  • Save tsteur/6003974 to your computer and use it in GitHub Desktop.
Save tsteur/6003974 to your computer and use it in GitHub Desktop.
Simple build configuration file for Titanium Mobile Alloy. It extends the destroy method of each controller to automatically remove all event listeners which are defined in the view (XML).
function readContentFromFile(file)
{
return require('fs').readFileSync(file).toString();
}
function writeContentToFile(file, content)
{
require('fs').writeFileSync(file, content);
}
function isJsFile(filename)
{
return (filename.match(/\.js$/));
}
function buildRemoveEventListenerCalls(content)
{
var regex = /__defers(.*)\$(.*)\.addEventListener\((.*)\,\s(\w*)\)/gm;
var cleanupCalls = [''];
var match = null;
while (match = regex.exec(content)) {
var widget = '$' + match[2]; // $.__views.index
var listener = match[3]; // "click"
var callback = match[4]; // methodToCallOnClick
var parameter = '(' + listener + ', ' + callback + ');'; // ("click", methodToCallOnClick);
var funcToCall = widget + '.removeEventListener'; // $.__views.index.removeEventListener
cleanupCalls.push(widget + ' && ' + callback + ' && ' + funcToCall + ' && ' + funcToCall + parameter);
}
cleanupCalls.push('');
return cleanupCalls.join('\n');
}
function extendControllerDestroyMethodToRemoveEventListener(jsFile)
{
var resourceContent = readContentFromFile(jsFile);
var cleanupCalls = buildRemoveEventListenerCalls(resourceContent);
var destroyMethod = 'exports.destroy = function() {';
var replacedContent = resourceContent.replace(destroyMethod, destroyMethod + cleanupCalls);
writeContentToFile(jsFile, replacedContent);
}
function extendAllControllersDestroyMethodToRemoveEventListener(dir)
{
var path = require('path');
var wrench = require('wrench');
var resourcesPath = dir.resources + '/alloy/controllers';
wrench.readdirSyncRecursive(resourcesPath).forEach(function(target) {
if (!isJsFile(target)) {
return;
}
var jsFile = path.join(resourcesPath, target);
extendControllerDestroyMethodToRemoveEventListener(jsFile);
});
}
task("post:compile", function(event, logger) {
extendAllControllersDestroyMethodToRemoveEventListener(event.dir);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment