Skip to content

Instantly share code, notes, and snippets.

@iotashan
Created December 15, 2011 02:45
Show Gist options
  • Save iotashan/1479601 to your computer and use it in GitHub Desktop.
Save iotashan/1479601 to your computer and use it in GitHub Desktop.
Creating a CommonJS singleton with Titanium
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
var firstCall = require('TestSingleton');
var NewWin = require('NewWin');
var win1 = Titanium.UI.createWindow({
title:'Win 1',
backgroundColor:'#fff'
});
var label1 = Titanium.UI.createLabel({
color:'#999',
text:firstCall.pullString(),
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win1.add(label1);
win1.open(); // open first window
// open second window on click
win1.addEventListener("click",function(){
firstCall.updateString("singleton value was updated"); // update the private string in the singleton
win2 = new NewWin();
win2.open();
});
var secondCall = require('TestSingleton');
var NewWindow = function() {
var win = Titanium.UI.createWindow({
title:'Win 2',
backgroundColor:'#c00'
});
var label1 = Titanium.UI.createLabel({
color:'#999',
text:secondCall.pullString(),
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win.add(label1);
return win;
};
module.exports = NewWindow;
var TestSingleton = (function(){
var private_string = "initial singleton value";
function updateString(str) {
private_string = str;
};
function pullString() {
return private_string;
};
return {
updateString:updateString,
pullString:pullString,
};
})();
module.exports = TestSingleton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment