HittmanA
HittmanA

Reputation: 179

How to use and update NativeScript ListView

I am trying to figure out how to use NativeScript's ListView and I can not figure out how. I have yet to find any good tutorials and really need help. I need to be able to show and update (add and subtract items from) a ListView in NativeScript. Thanks in advance!

Upvotes: 2

Views: 1826

Answers (1)

Dean Le
Dean Le

Reputation: 2094

You can mostly find all the things about the ListView here but I will make a demonstration of ListView practice that I'm using in my app. I'm using MVC structurce so we will have page.xml, page.js and page-viewmodel.js. In page.xml, we will want to have a listview with like this:

<Page>
 <ListView items="{{ myItems }}" loadMoreItems="loadMore">
    <ListView.itemTemplate>
       <Label text="{{ message }}" textWrap="true" />
    </ListView.itemTemplate>
 </ListView>
</Page>

The <ListView.itemTemplate> is where you define a prototype for an item of data array. You can use a normal array but I suggest using built-in class called ObservableArray for programmatically changing of any item or any property later on.

In the model, which is page-viewmodel.ts, we have:

var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;

public class PageViewModel extends Observable {
    private _myItems = new ObservableArray<MyItem>()

    get myItems(): {
        return this._myItems
    }

    public loadItems() {
        var dataArray = ["Red", "Blue", "Green"];
        for (var i in dataArray) {
            var item = MyItem(dataArray[i])
            this._myItems.push(item);
        }
    }
}
var pageViewModel = new PageViewModel();


public class MyItem extends Observable {
    public message: String;

    constructor(value) {
        this.message = value;
    }
}

Finally, in the controller which is page.ts:

import {pageViewModel} from "./page-viewmodel"

exports function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = pageViewModel
}

exports function loadMore(args) {
    pageViewModel.loadItems();
}

In conclusion, you define the ListView as well as its prototype in XML. After that, the viewmodel (which is an Observable object) is where you handle the data(add item, delete item, load items from backend, etc). Finally, you import that viewmodel to the controller(page.js) and bind to page.bindingContext so that the XML can receive the data

P/S: I'm writing this in TypeScript. In Javascript, the implementation is basically the same, there are just a bit of difference in the syntax. For example here is how the page.js would look like:

var pageViewModel = require("./page-viewmodel");

function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = pageViewModel
}
exports.pageLoaded = pageLoaded;

Upvotes: 2

Related Questions