Knockout checkbox change event sends old value

后端 未结 3 1729
小鲜肉
小鲜肉 2021-02-01 15:10

I\'m having a problem with knockout \"checked\" binding. It seems that \"change\" event at checkbox return old value, before it is updated(so if it was unchecked it will return

3条回答
  •  灰色年华
    2021-02-01 15:37

    Try using subscribe instead of event binding. This should work now

    var Category = function (Id, Name, Order, ShowOpened) { this.Id = Id; this.Name = Name; this.Order = Order; this.ShowOpened = ko.observable(ShowOpened); this.IsUpdated = false; this.OldOrder = Order; this.OldShowOpened = ShowOpened; this.ShowOpened.subscribe(function (newShowOpened) { if(this.Order != this.OldOrder || this.ShowOpened() != this.OldShowOpened) this.IsUpdated = true; else this.IsUpdated = false; }, this); }; var ViewModel = { Categories: ko.observableArray([]) }; ko.applyBindings(ViewModel);

    Or as alternative (and in my opinion a better solution) you can use dependentObservable, now called computed. Here's how it would look like

    var Category = function (Id, Name, Order, ShowOpened) { this.Id = Id; this.Name = Name; this.Order = Order; this.ShowOpened = ko.observable(ShowOpened); this.OldOrder = Order; this.OldShowOpened = ShowOpened; this.IsUpdated = ko.computed(function () { return this.Order != this.OldOrder || this.ShowOpened() != this.OldShowOpened; }, this); }; var ViewModel = { Categories: ko.observableArray([]) }; ko.applyBindings(ViewModel);

提交回复
热议问题