Sneaky Includes inside Methods
I'm familiar with this handy bit of code:
Ti.include("includes/database.js");
…but I'm wondering if there's a way to do an include inside a method like this:
var myField = Titanium.UI.createTextField({
Ti.include("includes/textFieldStyle.js");
});
…and then textFieldStyle.js would have something like:
color:'#FFF',
borderRadius:6
Is there a way to pull that off?
It would make it much more convenient to define a global style for a textField and just include all the attributes each time instead of copying and pasting them all.
Any ideas?
2 Answers
-
How I do this type of thing:
First, define my styles in a styles.js that I Ti.include at the start of my app, eg:
var textFieldStyle = { color: '#FFF', borderRadius: 6 };
Then I roll an extension to the main Object class like so:
Object.prototype.mergeDefaults = function(source) { for (var property in source) { if (this[property] === undefined) { if (source[property] && source[property].constructor && source[property].constructor === Object) { this[property] = this[property] || {}; this[property].mergeDefaults(source[property]); } else { this[property] = source[property]; } } } return this; };
Now, when defining a new text field, I can do this:
var myField = Titanium.UI.createTextField({ color: '#00FF00' // Overrides default }.mergeDefaults(textFieldDefaults));
Handy!
-
Open file, evaluate file contents, sorry for shorthand. On mobile