【问题标题】:Nativescript Switch prevent change event firing on initial bindingNativescript Switch 防止在初始绑定时触发更改事件
【发布时间】:2017-04-28 09:01:24
【问题描述】:

嗨,我的模板如下所示

<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,如何处理?

注意:Nativescript 初学者

【问题讨论】:

标签: nativescript angular2-nativescript


【解决方案1】:

我为克服这个问题所做的就是关注tap 事件而不是checkedChange

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

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

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

【讨论】:

    【解决方案2】:

    我遇到了类似的问题:从 API 加载设置数据,并针对我从 api 设置的值触发 checked 事件——这在我的情况下是不可取的。我没有看到防止事件在初始绑定上触发的好方法,所以我决定简单地忽略事件,直到我知道它们是来自实际使用开关的用户的合法事件。

    我通过使用属性switchReady 来跟踪您想要开始识别更改事件的时间。此模式还会使切换保持禁用状态,直到您准备好开始接受更改。这利用了 Switch 的 isEnabled 属性,参见 docs here

    标记

    <Switch [checked]="currentSettings.pushTurnedOn" [isEnabled]="switchReady" (checkedChange)="onPushSettingChange($event)" row="0" col="1"></Switch>
    

    组件

    export class SettingsComponent implements OnInit {
      currentSettings: Settings = new Settings(false)    
      switchReady: boolean = false
    
      ngOnInit() {
        this.getCurrentSettings()
      }
    
      public onPushSettingChange(args) {
        let settingSwitch = <Switch>args.object
    
        if (settingSwitch.isEnabled) {
          // do something with the event/change    
        } else {
          // we aren't ready to accept changes, do nothing with this change          
          return
        }
      }
    
      getCurrentSettings() {
        this.settingsService.loadCurrentSettings().subscribe(
          () => {
            this.currentSettings = this.settingsService.currentSettings
            // we've applied our api change via data binding, it's okay to accept switch events now
            this.switchReady = true
          },
          err => alert('There was a problem retrieving your settings.')
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 2012-05-05
      相关资源
      最近更新 更多