Accessing object values from an ObservableArray and displaying them in a Label

I'm having trouble accessing the values of objects stored in an ObservableArray:

const observable = require("tns-core-modules/data/observable");
const ObservableArray = require("tns-core-modules/data/observable-array").ObservableArray;

var myArray = new ObservableArray([]);

var pageData = observable.fromObject({
    myArray: myArray
});

exports.onLoad = function (args) {
    const page = args.object;
    page.bindingContext = pageData;
    // a Bluetooth plugin returns a peripheral object
    myArray.push(peripheral);
    //console.log(Object.keys(peripheral));
}

The console.log() function prints the peripheral object like this:

JS: [type, UUID, name, RSSI, state, advertisement, manufacturerId, manufacturerData]

This is my XML file:

<Page loaded="onLoad">
    <ListView items="{{ myArray }}">
        <ListView.itemTemplate>
            <StackLayout>
                <Label text="{{ peripheral['UUID'] }}"/>
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
</Page>

The ListView items are loading just fine, but I can't get the Label to show any value of the peripheral object. I'm pretty sure the peripheral['UUID'] syntax is wrong but I can't find information on how to access this data...

Any help or pointers in the right direction would be greatly appreciated.

2 answers

  • answered 2018-11-08 07:34 Manoj

    peripheral was just your variable name that does not exists in the array. Simply bind the UUID.

    <Page loaded="onLoad">
    <ListView items="{{ myArray }}">
        <ListView.itemTemplate>
            <StackLayout>
                <Label text="{{ UUID }}"/>
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
    </Page>
    

  • answered 2018-11-08 07:38 philSch

    Ok, after some coffee and more trial and error the solution is pretty simple:

    <Page loaded="onLoad">
        <ListView items="{{ myArray }}">
            <ListView.itemTemplate>
                <StackLayout>
                    <!-- just using 'UUID' here -->
                    <Label text="{{ UUID }}"/>
                </StackLayout>
            </ListView.itemTemplate>
        </ListView>
    </Page>
    

    Apparently the values of objects in an ObservableArray are just visible to the XML file. You just have to use the name of the value, in my case it was UUID or name.

    I clearly have to read up on the mechanics behind observables, right now this seems like magic to me.