Titanium Alloy: Accessing UI from different controllers?
Asked Answered
F

1

6

I seem to be having trouble updating objects in Titanium Appcelerator Alloy,

I basically want to be able to add a table row to a table that is in a different controller/view that i am currently in..... hopefully the below will better describe this :s

basket.xml

<Alloy>
    <Window id="basketWindow" class="container">
        <TableView id="basketTable" />
        <Button id="addItemButton" onClick="addItem">Add Item</Button>
    </Window>
</Alloy>

basket.js

function addItem()
{
    var itemList = Alloy.createController('item_list');

    itemList.getView().open();
}

item_list.xml

<Alloy>
    <Window id="itemListWindow" class="container">
        <TableView id="itemListTable">
            <TableViewRow id="item1" className="item" onClick="addItemToBasket">
                Test Item
            </TableViewRow>
        </TableView>
    </Window>
</Alloy>

item_list.js

function addItemToBasket()
{
    var row = Ti.UI.createTableViewRow({title: 'Test Item'});

    // Here i would ideally want to put something like $.basketTable.append(row);
    // But nothing happens, im guessing it cant find $.basketTable as its in a different controller?

}

Does anyone know away around this?

Thanks for reading :)

Franchot answered 17/4, 2013 at 14:10 Comment(0)
B
7

One simple, easy solution is to just trigger an app wide event when you add an item to the basket:

function addItemToBasket() {
    Ti.App.fireEvent("app:itemAddedToBasket", {
       title : "Test Item", 
       otherAttribute : "Value"
    });
}

Then listen for the event in the basket controller somewhere, and add the table row:

// inside basket.js
Ti.App.addEventListener("app:itemAddedToBasket", function(e) {
    // object 'e' has all the row information we need to create the row
    var row = Ti.UI.createTableViewRow({
        title: e.title, 
        otherAttribute: e.otherAttribute
    });
    // Now append it to the table
    $.basketTable.append(row);
});
Bromate answered 18/4, 2013 at 3:27 Comment(3)
I like this answer, but I am also curious as to a more "Model-View-Controller" way of doing this. Suppose 'Basket' was a Model or a Collection and I want automatic syncing with a server. Would app-level events still be a good solution?Gouge
An app level event could trigger a global sync event that the "model" changed, this trickles down informing each controller the model has changed, and then updates its view. So some of the same concepts apply. Although "app level event" would probably be replaced by a Backbone event on the basket collection.Bromate
Hi Josiah, Can you please look at my question here #30951969Paddock

© 2022 - 2024 — McMap. All rights reserved.