淘汰赛复选框更改事件发送旧值 [英] Knockout checkbox change event sends old value
问题描述
我在敲除检查"装订时遇到问题.似乎复选框中的更改"事件在更新之前会返回旧值(因此,如果未选中,它将返回false).我不认为我可以订阅该值,因为我将其包含在对象中.
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 false). I don't think that I can subscribe to the value since I have it inside object.
<tbody data-bind="foreach: Categories">
<tr>
<td><input type="checkbox" data-bind="checked: ShowOpened, event: { change: $root.CategoryChange }" /></td>
</tr>
</tbody>
<script type="text/javascript">
var Category = function (Id, Name, Order, ShowOpened) {
this.Id = Id;
this.Name = Name;
this.Order = Order;
this.ShowOpened = ShowOpened;
this.IsUpdated = ko.observable(false);
this.OldOrder = Order;
this.OldShowOpened = ShowOpened;
};
var ViewModel = {
Categories: ko.observableArray([]),
CategoryChange: function(pCategory) {
if(pCategory.Order != pCategory.OldOrder || pCategory.ShowOpened != pCategory.OldShowOpened)
pCategory.IsUpdated(true);
else
pCategory.IsUpdated(false);
}
};
ko.applyBindings(ViewModel);
</script>
因此,在此示例中,我具有ShowOpened复选框,该复选框可以触发CategoryChange方法,该方法将更改对象内部的变量(稍后需要知道要更新的对象).但是,更改chechbox时,它始终会发送旧值,触发方法,然后再更改该值.有什么办法可以解决这个问题?
So in this example I have ShowOpened checkbox that can trigger CategoryChange method that will change a variable inside object(that I need later to know what object are updated). But when the chechbox is changed it always send out the old value, triggering method, and then changes the value. Is there any way to fix this?
推荐答案
由于您坚持认为缺少ko.observables
并不是问题,因此我仔细研究了一下.看来,你是对的! change
事件在设置实际值之前之前被触发.恐怕我不知道原因.
Since you persisted on stating that the lack of ko.observables
is not an issue, I've looked at it closer. It seems, that you are correct! The change
event is fired before the actual value is set. I'm afraid I do not know the reason for this.
但是有一种简单的方法可以解决此问题:只需将change
事件更改为click
事件:
But there is an easy way to fix this: just change change
event to click
event:
<input type="checkbox" data-bind="checked: ShowOpened, click: $root.CategoryChange" />
请记住,您必须将return true;
明确放在click
事件处理程序的末尾.否则,新值将不会设置为复选框.
Remember, that you have to explicitly put return true;
at the end of click
event handler. Otherwise the new value won't be set to checkbox.
如果您不想使用click
事件,则可以使用另一种方法.订阅ShowOpened
的更改:
If you do not want to use click
event, then you can do it the other way. Subscribe to changes of ShowOpened
:
this.ShowOpened = ko.observable(ShowOpened);
this.ShowOpened.subscribe(function(newValue) {
/* Do something when ShowOpened changes.
newValue variable holds the new value, obviously. :) */
});
这篇关于淘汰赛复选框更改事件发送旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!