无法使用jQuery触发淘汰赛数据绑定 [英] Not able to trigger Knockout data-bind using jQuery

查看:78
本文介绍了无法使用jQuery触发淘汰赛数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery和淘汰赛编写插件.我有两个单选按钮.我正在使用敲除数据绑定来检查和取消选中单选按钮.问题是,当我尝试使用jQuery单击另一个按钮时取消选中单选按钮时,它没有更新bind observable属性.

I am writing a plugin using jQuery and knockout. I have two radio buttons. I am using knockout data-bind to check and uncheck the radio button. The problem is that when I am trying to uncheck the radio button on click of another button using jQuery, it is not updating bind observable property .

<input  type="radio" data-bind="checked: selectedVal" name="1" value="fixedPrice"/>  Fixed Price
 <input class="hn" type="radio" data-bind="checked: selectedVal" name="1" value="allowBiding"/> Allow Biding
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
<input type="button" id="button" value="Click Me" />

 var onClick = function() {
   $('.hn').prop('checked', true);

};

$('#button').click(onClick);

var ViewModel = function () {
    var self = this;
    self.selectedVal = ko.observable("fixedPrice");
    self.selectedVal.subscribe(function (val) {
       console.log(val)
    });
};

ko.applyBindings(new ViewModel());

请在下面找到此jsfiddle ,并提供更多详细信息.

Please find this jsfiddle below with more details.

推荐答案

欢迎光临!不要以这种方式混合KO和jQuery.您是战斗淘汰赛,没有使用它.参见我之前写的这个答案,了解非常相似的情况和扩展的解释.

Welp! Don't mix KO and jQuery in this way. You're fighting Knockout, not using it. See this earlier answer I wrote for a very similar situation and extended explanation.

请注意,这肯定是 not 的错误,jQuery默认会在此类DOM更改上触发 not 触发事件.如果您坚持以这种方式混合KO和jQuery,请确保像这样通知其他人:

Note that this is certainly not a bug, jQuery will by default not trigger events on DOM changes like that. If you insist on mixing KO and jQuery this way, be sure to notify others like this:

ko.applyBindings({
  isChecked: ko.observable(false),  
  onClick: function() {
    $('.hn').prop('checked', true);
    $('.hn').trigger('click');
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1. The radio button: <input type="radio" class="hn" data-bind="checked: isChecked">
<br>
2. Trigger it with jQuery: <button data-bind="click: onClick">trigger</button>
<hr>
Debug info:<br><textarea data-bind="text: ko.toJSON($root)"></textarea>

这篇关于无法使用jQuery触发淘汰赛数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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