Alex Souza
Alex Souza

Reputation: 27

Nativescript ListView Refresh

I need to update my ListView constantly but, for some reason, I couldn't identify yet, I haven't been successful doing so.

dash.xml

<ListView id="pilotList" items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout columns="*,*2,*">
            <Label text="{{ listNick }}" col="1"  class="listNick" />
            <Label text="{{ listDistance }}" col="2" class="listDistance" />
       </GridLayout>
    </ListView.itemTemplate>
</ListView>

dash.js (I am extracting just the related parts here):

var observable = require("data/observable");
var pageModule = require("ui/page");

var activePilots = []; //this is the array with the contents


exports.pageLoaded = function(args) {
    page = args.object;  
    pilotList = page.getViewById("pilotList");  
    page.bindingContext = { activeList:activePilots };
}

Later on in the code (every time a location change), I update the activePilots array:

activePilots.push({listNick:fbMi, listDistance:result.value[uid]["uid"] })

So far, everything is working as I can see with the console.log(JSON.stringify(activePilots)).

However, the ListView never updates, even forcing the

pilotList.refresh();

Any ideas of what I am doing wrong? Thanks, Alex

Upvotes: 1

Views: 5089

Answers (1)

Nick Iliev
Nick Iliev

Reputation: 9670

Few things that needed to be addressed. In order to update values in your UI, you need to use an Observable model and data binding. e.g. page.js

var observable = require("data/observable");
var viewModel = new observable.Observable();
viewModel.set("activeList", [1,2,3]);

page.xml

<ListView items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout>
            <Label text="{{ $value}}"  />
       </GridLayout>
    </ListView.itemTemplate>
</ListView>

Now notice that with this approach you will still not be able to update your list view items when using push for the array. The reason - the list itself is Observable but the property change will be triggered only if your change the whole array and won't be triggered when using arr.push.

To be able to update your list-view items when adding new items to your array you will need to use an ObservableArray e.g.

var ObservableArray = require("data/observable-array").ObservableArray;
var viewModel = new observable.Observable();
viewModel.set("activeList", new ObservableArray ([1,2,3]));

Now the array is observable meaning you can add new items on the fly and they will be rendered in your ListView. Demo application using Observable and Observable array can be found here - the application is written in TypeScript - just execute tns run android and the respective JavaScript files will be created after the transpilation.

Upvotes: 4

Related Questions