Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

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?

— asked June 25th 2010 by Clifton Labrum
  • include
  • method
0 Comments

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!

    — answered April 7th 2011 by Rob Morris
    permalink
    0 Comments
  • Open file, evaluate file contents, sorry for shorthand. On mobile

    — answered June 26th 2010 by Ryan Tregea
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.