2016-12-15 56 views
0

我對Nativescript事件處理有點困惑。我正在使用typescript與清晰的代碼隱藏和viewmodel分離,並且我試圖將itemTap屬性綁定到viewmodel方法(就像在https://github.com/NativeScript/template-hello-world-ts/blob/master/main-view-model.ts中所示的示例中一樣)。在NativeScript的ViewModel方法中綁定itemTap

XML:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="pageLoaded" class="page"> 
    <StackLayout> 
    <ListView items="{{ items }}" itemTap="onItemTapped"> 
     <ListView.itemTemplate> 
     <Label text="{{ Name }}"/> 
     </ListView.itemTemplate> 
    </ListView> 
    </StackLayout> 
</Page> 

代碼隱藏:

import { EventData } from 'data/observable'; 
import { Page } from 'ui/page'; 
import { EditItemViewModel } from '../../ViewModels/EditItemViewModel'; 

export function navigatingTo(args: EventData) { 
    let page = <Page>args.object; 
    page.bindingContext = new EditItemViewModel(); 
} 

視圖模型:

import { Observable } from 'data/observable'; 
import { ObjectRelationalMapper } from '../Common/Data' 
import { WebServiceDataManager } from '../Common/Data' 

import { Item } from '../Models/Item'; 

export class EditItemViewModel extends Observable { 
    _wsDataManager: WebServiceDataManager; 
    _orm: ObjectRelationalMapper; 
    _items: Array<Item>; 

    get items(): Array<Item> { 
    return this._items; 
    } 

    set items(items: Array<Item>) { 
    this._items = items; 
    } 

    constructor() { 
    super(); 
    this._wsDataManager = new WebServiceDataManager(); 
    this._orm = new ObjectRelationalMapper(); 
    this.listAllItems(); 
    } 

    private listAllItems(): void { 
    this._orm.getAllObjects(Item, this, this.onItemsReceived) 
    } 

    public onItemsReceived(items: Array<Item>) { 
    this._items = items; 
    this.notify({ object: this, eventName: Observable.propertyChangeEvent, propertyName: 'items', value: this._items }); 
    } 

    public onItemTapped(args): void { 
    let tappedView: any = args.view; 
    let tappedItem: Item = tappedView.bindingContext; 
    } 
} 

而且onItemTapped方法不被解僱。如果我把代碼隱藏在後面:

export function onItemTapped(args): void { 
    let tappedView: any = args.view; 
    let tappedItem: any = tappedView.bindingContext; 
} 

..它按預期工作。在viewModel中使用事件處理程序有什麼問題,爲什麼helloworld的例子如此具有誤導性?

回答

4

的事情是,在你的onItemTapped第一種情況是從您的視圖模型來,所以你應該引用它就像你正在使用雙大括號引用視圖模型屬性項目意義:

<ListView items="{{ items }}" itemTap="{{ onItemTapped }}"> 

現在,如果onItemTapped功能被放置在您的代碼隱藏文件,那麼你可以直接引用它寫在你的代碼

<ListView items="{{ items }}" itemTap="onItemTapped">