【问题标题】:Get context of a tapped list item in Nativescript在 Nativescript 中获取点击列表项的上下文
【发布时间】:2017-05-15 18:57:59
【问题描述】:

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

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 我如何才能对我感兴趣的那个进行特定引用,我可以给它一个类并访问是这样吗?

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

【问题讨论】:

    标签: javascript nativescript


    【解决方案1】:

    您不需要单独的类,只需有一个与该页面对应的 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];
    }
    

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      相关资源
      最近更新 更多