Question

In Alloy Titanium, I can access XML elements with their id $.element_id but how do I get elements by their class ?

I have

<View id="main" layout="horizontal" horizontalWrap="true">
    <Button left="4%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
    <Button left="13%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
    <Button class="top30" left="4%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
    <Button class="top30" left="13%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
    <Button class="top30" left="4%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
    <Button class="top30" left="13%" width="125dp" height="125dp" backgroundImage="menus/woodblock.png"></Button>
</View>

And I want to get all class="top30"

Was it helpful?

Solution

There is no way in Alloy to access views directly by using their class except by iterating over all possible views on the screen and checking their className value.

If all your views with class="top30" are children of the same view you can try using Titanium.UI.View.children property:

var i, view
for (i in $.main.children) {
    view = $.main.children[i];
    if (view.className === 'top30') {
        /* Do your operation here */
    }
}

OTHER TIPS

I took the daninula posted and refactored it into a commonJS module. Untested but could be useful.

Find it here: https://gist.github.com/shouse/06f447884fbc85ec122c

Or just try the code:

/**
 * @method getViewByClass
 * This will take a class and an optional parent and find children with that class
 * Untested but will likely work
 * @param {String} _class Class name
 * @param {Object} _parent Optional param to specify parent to iterate through
 */ 
exports.getViewByClass = function(_class, _parent) {
    _parent = _parent || $.main;
    var classArray = [];
    _.each(_parent.children, function(child){
        if (child.className === _class) {
            classArray.push(child);
        }
    });

    return classArray;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top