Nativescript Switch 防止在初始绑定时触发更改事件 [英] Nativescript Switch prevent change event firing on initial binding

查看:22
本文介绍了Nativescript Switch 防止在初始绑定时触发更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板如下

<ListView [items]="modules">
    <template let-item="item" >
        <StackLayout orientation="vertical">
                <Switch (checkedChange)="onSwitchModule(item.id,$event)" [checked]="item.active"></Switch>
        </StackLayout>
    </template>
</ListView>

我的控制器是

ngOnInit() {
    this._moduleService.getUserModules()
        .subscribe(
            response=>{
              this.modules = response.data;
            }
        )

}

onSwitchModule(itemId) {
   console.log(itemID); //Gets called on initial true binding on switch checked
}

每次页面加载时都会调用 onSwitchModule 并且 item.active 在任何项目上为 true,如何处理?

The onSwitchModule get called everytime the page loads with item.active is true on any item, how to handle this ?

注意:Nativescript 初学者

NOTE: Beginner in Nativescript

推荐答案

我为克服这个问题所做的是观察 tap 事件而不是 checkedChange:

What I did to overcome this is I watch for tap events instead of checkedChange:

<Switch (tap)="switchClicked" [checked]="item.active"></Switch>

并且在回调中,您可以从 bindingContext 获取当前项:

and in the callback, you can get the current item from bindingContext:

function switchClicked(args) {
  const item = args.object.bindingContext.item;
}

这篇关于Nativescript Switch 防止在初始绑定时触发更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆