我已经开始使用本机脚本了,我对MVVM概念有点困难,尤其是绑定 . 我有使用TypeScript的设置环境 .
我有一个HomePage,我需要创建一个水平的按钮列表 . 但是,首先我需要从服务器获取我需要显示的按钮:
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();
});
}
和 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;
}
}
在 main.xml
我有这个:
<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>
我注意到的是,当我启动我的应用程序时,最初列表是空的(如预期的那样),但在我向 onMapReady()
函数中的存储库询问按钮并调用 viewModel.categories = result.getCategories()
之后,列表仍为空 .
现在,如果我在XML中更改并保存,则NativeScript CLI将使用设备同步该更改,它不会重新创建页面,而只是重新创建视图,然后由于对 MainViewModel
对象的引用没有丢失,并且它在 categories
字段中包含这些按钮,它实际上会显示出来......所以我看到它的问题是,当我设置属性 categories
时,监听器不会收到有关此更改的通知,因此视图未更新以显示非空的按钮列表...我猜我绑错了......
我该如何解决这个问题?我认为它与ObservableArray有关,但我不确定它应该如何实现?
1 回答