Search code examples
titaniumappceleratorappcelerator-titaniumtitanium-alloy

Titanium Alloy: Run a function that exists in a require statement


I have the following code:

index.xml

<Window>
    <View>
        <Require id="foo1" src='foo'>            
    </View>
</Window>

foo.xml

<View>
    <Label>This is from foo</Label>
</View>

foo.js

function doSomething() {
    Ti.API.info('YES!');
}

Question

I want to be able to run the function doSometing() in index.js. How can I do that?

I tried:

$.foo1.doSomething()

But that does not seem to work.


Solution

  • <Window>
        <View>
            <Require id="foo1" src='foo'>            
        </View>
    </Window>
    

    In this code, Require id holds the controller of foo.js file, means,

    $.foo1 = $ in foo.js

    In order to access any property or method from Require, you can attach that property to any view or just export it like this:

    foo.js

    $.doSomething = function () {
        Ti.API.info('YES!');
    }
    

    index.js

    $.foo1.doSomething();
    

    In case of above @miga's answer, you need to use this code in index.js :

    // view is the id of topmost view to which you attached the method.
    $.foo1.view.doSomething();