在 Nativescript 中获取点击列表项的上下文

Get context of a tapped list item in Nativescript

是否可以获取列表视图中点击项目的上下文?例如,如果我有一个包含三个项目的列表,我如何知道它是单击的第二个项目并从可观察数组中与该项目相关的对象中获取数据?

EX:这是我的列表模板,如果用户点击连接列表中的第二个连接,我如何根据点击的项目索引获取与该连接关联的数据?

  <ListView items="{{ connections }}"  loaded="" itemLoading="" itemTap="">
      <ListView.itemTemplate>
          <StackLayout class='connection-li'>
                <GridLayout class="connection-info" rows="" columns="auto, *, *" tap="goToMeasurements">
                    <Image col="0" src="res://ic_person_black_36dp" stretch ="none" />                        
                    <Label col="1" class="connection-name" text="{{ PatientFirstName + ' ' + PatientLastName }}" textWrap="false" />
                    <Image col="2" verticalAlignment="middle" horizontalAlignment="right" src="res://ic_cancel_black_18dp" stretch ="none" />                        
                </GridLayout>                                                       
          </StackLayout>
      </ListView.itemTemplate>
  </ListView>

编辑: 根据文档,我发现了以下事件,我可以挂钩它以获取索引数据,但是它引用 ListView 的地方我如何才能使它成为我感兴趣的对象的特定引用,我可以给它一个 class 并以这种方式访问​​它?

listView.on(listViewModule.ListView.itemTapEvent, function (args: listViewModule.ItemEventData) {
    var tappedItemIndex = args.index;
    var tappedItemView = args.view;
    //// Do someting
});

您不需要单独的 class,只需要一个与此页面对应的 javascript 文件(即 main-page.xml 和 main-page.js) .然后,您可以在 itemTap 属性中连接事件:

<ListView items="{{ connections }}" itemTap="onConnectionTapped">

然后从相应的 javascript 文件导出该事件,您可以通过几种不同的方式访问该项目的数据对象:

export function onConnectionTapped(args) {
    var tappedView = args.view,
        //the View will have a bindingContext 
        // set to the individual item from the list
        tappedItem = tappedView.bindingContext;

    //or, if you need the entire list as well, 
    // get it from the Page's bindingContext
    // as each View has a ref to the Page it's on
    var pageBindingContext = tappedView.page.bindingContext,
        fullItemsList = pageBindingContext.connections,
        itemForTap = fullItemsList[args.index];
}

goToMeasurements 处理程序中 args.object 将是 GridLayout。它的 .bindingContext 属性 将是您的 connections 数组中的一个数据项。 connections.indexOf(dataItem) 将 return 这个数据项的索引,如果你需要它的索引。