Knockout.Js无法检测到以编程方式更改的复选框状态 [英] Knockout.Js doesn't detect programmatically changed checkbox state

查看:72
本文介绍了Knockout.Js无法检测到以编程方式更改的复选框状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的复选框,其值由我正在编写的一些基础结构调整以保持localStorage的状态.我知道通常可以通过设置viewModel来完成,但是 基础架构不知道任何敲除绑定并且无法访问它们.

I have a simple checkbox which has its value adjusted by a bit of infrastructure that I'm writing to persist state in localStorage. I am aware that this would normally be done by setting the viewModel but the infrastructure is unaware of any knockout bindings and has no access to them.

我认为这不是问题,因为我认为淘汰赛正在'change'事件中发生,但是$checkbox.prop('checked', true).trigger('checked')未能触发我的观察结果.即使直接使用click事件也无法完全满足我的需求.

I didn't think this would be a problem as I assumed that knockout was running off the 'change' event, however $checkbox.prop('checked', true).trigger('checked') fails to trigger my observable. Even using the click event directly doesn't get me quite what I need.

敲除线会发生什么事件?如何获取它以读取控件的状态?

What events does knockout wire to? How do I get it to read the state of the control?

jsbin在这里显示了这种奇怪的行为.尝试直接选择复选框而不是单击按钮.

jsbin showing this weird behavior here. Try selecting the checkbox directly versus clicking the button.

推荐答案

在我看来,这与jquery错误有关.我带到github淘汰赛问题跟踪器进行了追踪; 请参阅此处.

In my case this turned out to be related to a jquery bug. I took to the github knockout issue tracker to track this down; see here.

最终我最终在我的组件中这样做了:

Ultimately I ended up doing this in my component:

var isjQueryOld = /^(0|1)\.[0-8]\./.test($.fn.jquery); // <=1.8.*
var toggleCheckbox = isjQueryOld ? jQueryOldToggleCheckbox : function($el) { $el.trigger('click') } //https://github.com/knockout/knockout/issues/987


function jQueryOldToggleCheckbox($el) {
    //This should be simple right? See http://stackoverflow.com/a/8595601/5056
    //and "simulating events to adjust knockout models" jasmine spec
    //all this is nessessary to get everything working with knockout
    var changeTo = !$el.prop('checked');
    if(changeTo)
        $el.attr('checked', true);
    else
        $el.removeAttr('checked');
    $el.trigger('click');
    $el.prop('checked', changeTo);
}

以及我的代码

        toggleCheckbox($el);

这篇关于Knockout.Js无法检测到以编程方式更改的复选框状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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