Created
July 15, 2013 22:12
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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