I am currently diving into the world of NativeScript and I find myself struggling a bit with the MVVM concept, specifically when it comes to binding. I have configured my environment to work with TypeScript.
On my HomePage, I am tasked with creating a horizontal list of buttons. However, before I can do that, I need to fetch the necessary button data from the server:
let page: Page;
let viewModel = new MainViewModel();
let fetchCategoriesUseCase: FetchCategoriesUseCase = new FetchCategoriesUseCase(new InMemoryCategoriesRepository());
export function navigatingTo(args: EventData) {
page = <Page>args.object;
page.bindingContext = viewModel;
}
export function onMapReady() {
console.log("Map is ready");
fetchCategoriesUseCase.handle(null).then((result: IFetchCategoriesResult) => {
viewModel.categories = result.getCategories();
});
}
and MainViewModel.ts
export class MainViewModel extends Observable {
private mMap: Observable;
private mCategories: Category[];
public constructor() {
super();
this.mMap = fromObject({
latitude: 42.442574,
longitude: 19.268646,
zoom: 13
});
}
get map(): Observable {
return this.mMap;
}
get categories(): Category[] {
return this.mCategories;
}
set categories(categories: Category[]) {
this.mCategories = categories;
}
}
In the main.xml
, I have the following setup:
<AbsoluteLayout>
<maps:mapView
left="0"
top="0"
width="100%"
height="100%"
latitude="{{ map.latitude }}"
longitude="{{ map.longitude }}"
zoom="{{ map.zoom }}"
mapReady="onMapReady"
cameraChanged="onMapCameraChanged"/>
<ScrollView
left="0"
top="0"
width="100%"
orientation="horizontal">
<Repeater items="{{ categories }}">
<Repeater.itemsLayout>
<StackLayout orientation="horizontal" />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<Button text="{{ getName() }}"/>
</Repeater.itemTemplate>
</Repeater>
</ScrollView>
</AbsoluteLayout>
As I observed, upon starting my application, the list is initially empty (which is expected), but even after fetching buttons in the onMapReady()
function and updating viewModel.categories
, the list remains empty.
However, if I make changes to the XML file and save it, the NativeScript CLI will sync the changes to the device without recreating the entire page. This results in the buttons being displayed because the reference to the MainViewModel
object was not lost and it contains the button data in the categories
field. It seems like the issue lies in how I bind the data...
How can I resolve this problem? I believe it might be related to using ObservableArray, but I'm unsure of the correct implementation?