Not able to trigger Knockout data-bind using jQuery
我正在使用 jQuery 和淘汰赛编写插件。我有两个单选按钮。我正在使用淘汰赛数据绑定来检查和取消选中单选按钮。问题是,当我尝试使用 jQuery 单击另一个按钮时取消选中单选按钮时,它没有更新绑定 observable 属性。
1 2 3 | <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 [cc lang="javascript"] |
var onClick = function() {
$(\\'.hn\\').prop(\\'checked\\', true);
};
$(\\'#button\\').click(onClick);
var ViewModel = 函数 () {
var self = this;
self.selectedVal = ko.observable("fixedPrice");
self.selectedVal.subscribe(function (val) {
控制台日志(val)
});
};
ko.applyBindings(new ViewModel());
[/cc]
请在下面找到此 jsfiddle 的更多详细信息。
jQuery 和 Knockout 正在争夺视图的控制权。如果您要使用视图模型,请使用视图模型,并且除了通过视图模型之外不要操作 DOM。你有一个控制单选按钮的 viewmodel 元素,你只需要设置它。 Knockout 提供了一个
1 2 3 4 5 6 7 8 9 10 11 12 | var ViewModel = function () { var self = this; self.selectedVal = ko.observable("fixedPrice"); self.selectedVal.subscribe(function (val) { console.log(val) }); self.setSelected = function () { self.selectedVal('allowBiding'); }; }; ko.applyBindings(new ViewModel()); |
1 2 3 4 | <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"> <input type="radio" data-bind="checked: selectedVal" name="1" value="fixedPrice" />Fixed Price <input type="radio" data-bind="checked: selectedVal" name="1" value="allowBiding" />Allow Biding [cc lang="javascript"] |
[/cc]
喂!不要以这种方式混合 KO 和 jQuery。您正在与淘汰赛战斗,而不是使用它。请参阅我为非常相似的情况和扩展解释而写的早期答案。
请注意,这肯定不是错误,jQuery 默认情况下不会在 DOM 更改时触发这样的事件。如果你坚持这样混合 KO 和 jQuery,一定要这样通知其他人:
1 2 3 4 5 6 7 | ko.applyBindings({ isChecked: ko.observable(false), onClick: function() { $('.hn').prop('checked', true); $('.hn').trigger('click'); } }); |
1 2 3 4 5 6 7 8 | <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 1. The radio button: <input type="radio" class="hn" data-bind="checked: isChecked"> 2. Trigger it with jQuery: <button data-bind="click: onClick">trigger</button> Debug info:<textarea data-bind="text: ko.toJSON($root)"></textarea> |
它看起来像一个错误。但是,您可以尝试调用本机单击处理程序,以便更新 observable。
1 | $('.hn').triggerHandler('click'); |
或
1 | $('.hn')[0].click(); |
这是一个 JsFiddle 演示