I'm beginning to refactor an app I'd written that used multiple windows defined in their own .js files and called by ...createUIWindow({ url:'xyz.js'}) style calls.
Thoughts are to preserve a lot of the work in the separate .js files, but 'require' them in as needed. I'm sensitive to issues of leaving a lot of global objects lying around that will eventually cause memory issues, so I would prefer to get this setup figured out correctly now and not have to redo again.
So for SDK 1.0.8.1 and iOS5 platform, does the following make sense for code separation, for memory, for performance, or would anyone suggest a different approach?
// app.js var myApp = require('/lib/myapp'); var rootWindow = Titanium.UI.createWindow(); var winHome = myApp.createHomeWindow(); var navGroup = myApp.createNavGroup(winHome); rootWindow.add(navGroup); rootWindow.open(); // lib/myapp.js module.exports={ someGlobalProp:'test', createHomeWindow : function() { var winHome = require('/lib/ui/winhome'); return winHome.buildWindow(); }, createNavGroup : function(w) { var navGroup = Titanium.UI.iPhone.createNavigationGroup({ window:w }); return navGroup; } }; // lib/ui/winhome.js module.exports = { buildWindow : function() { var w = Ti.UI.createWindow({ title:'Home', otherProps:'...' }); // build views, etc... add to window return w; } };and so on for other screens. All are built off initial home window and could be required in as needed. NavGroup should hopefully take care of cleaning up as they are exited. Thoughts?
1 Answer
Accepted Answer
Without seeing a lot more code I would say that you are along the right lines.
I will try and explain about the lack of global scope and memory management. Within commonJS there is no global scope so if you require a variable accessible across all windows then you would need to create a common module with the variable in and require it within each window.
This may seem like it is going to cause a memory leak, but the file is actually only loaded into memory once and used be the different files. You can do the same with common routines, again they will only be loaded into memory once.
however the module.exports should be exports.name { .... };
A few gotchas is that you need to be very strict about syntax, do not forget to close all elements etc with a ; or commonJS will complain.
so an example would be
common.js
exports.globalVars = { globalVar1: 'Hello World'; }; exports.commonFunc = function() { if (!android) { return true; } else { return false; }; };you can then require these in any other module and use them like
app.js
var inCommon = require ('common'); alert(inCommon.globalVars.globalVar1); alert(inCommon.commonFunc());So using this way enables you to have as many variables as you need and as many functions which can each be handled individually.
Hope this helps
T..
Your Answer
Think you can help? Login to answer this question!