NativeScript Core

Virtual Array

The VirtualArray is an advanced array-like class that helps to load items on demand. Through property loadSize and the itemLoadingEvent, the virtual array is used to load items only when needed.

Basics

VirtualArray Module Import

Using the VirtualArray requires the related module.

Note: Virtual array will divide total number of items to pages using loadSize property value. When you request an item at specific index the array will raise itemsLoading event with ItemsLoading argument index set to the first index of the requested page and count set to number of items in this page.

Inportant: If you have already loaded items in the requested page the array will raise multiple times itemsLoading event to request all ranges of still not loaded items in this page.

Creating New VirtualArray

const virtualArray = new VirtualArray(100);
virtualArray.loadSize = 15;

virtualArray.on(VirtualArray.itemsLoadingEvent, (args) => {

    // Argument (args) is ItemsLoading Interface.
    // args.index is start index of the page where the requested index is located.
    // args.count number of requested items.

    const itemsToLoad = [];
    for (let i = 0; i < args.count; i++) {
        itemsToLoad.push(i + args.index);
    }

    virtualArray.load(args.index, itemsToLoad);
});
const virtualArray = new VirtualArray(100);
virtualArray.loadSize = 15;

virtualArray.on(VirtualArray.itemsLoadingEvent, (args: any) => {

    // Argument (args) is ItemsLoading Interface.
    // args.index is start index of the page where the requested index is located.
    // args.count number of requested items.
    const itemsToLoad = [];
    for (let i = 0; i < args.count; i++) {
        itemsToLoad.push(i + args.index);
    }

    virtualArray.load(args.index, itemsToLoad);
});

Handling Array Changes

Handling change event when you load items using load() method.

virtualArray.on(VirtualArray.changeEvent, (args) => {
    // Argument (args) is ChangedData<T> Interface.
    console.log(args.eventName); // args.eventName is "change".
    console.log(args.action); // args.action is "update".
    console.log(args.removed.length); // args.removed.length and result.addedCount are equal to number of loaded items with load() method.
});
virtualArray.on(VirtualArray.changeEvent, (args: any) => {
    // Argument (args) is ChangedData<T> Interface.
    console.log(args.eventName); // args.eventName is "change".
    console.log(args.action); // args.action is "update".
    // args.removed.length and result.addedCount are equal to number of loaded items with load() method.
    console.log(args.removed.length);
});

Improve this document

Demo Source