Skip to content

Instantly share code, notes, and snippets.

@omorandi
Created September 6, 2011 13:27
Show Gist options
  • Save omorandi/1197528 to your computer and use it in GitHub Desktop.
Save omorandi/1197528 to your computer and use it in GitHub Desktop.
var CustomSwitch = function(onText, offText, value) {
// the custom view
var view = Ti.UI.createView();
var label = Ti.UI.createLabel();
var sw = Ti.UI.createSwitch();
view.add(label);
view.add(sw);
// this function returns the text to be shown in the label, based on val
var getLabelText = function(val) {
return (val ? onText : offText);
};
// this function updates the label and the switch based on val
var changeValue = function(val) {
label.text = getLabelText(val);
sw.value = val;
};
// when the switch changes its state we change the label and fire and event to the listeners
sw.addEventListener('change', function(e) {
changeValue(e.value);
view.fireEvent('change', e);
});
//initialize the state of our custom view
changeValue(value);
//Privileged method
view.changeValue = changeValue;
return view;
};
// we instantiate it as:
var my_switch = new CustomSwitch('switched on', 'switched off', true);
//my_switch is now a reference to the view created in the CustomSwitch() function
Ti.UI.currentWindow.add(my_switch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment