gpt4 book ai didi

javascript - KnockoutJS 使用 "checked"和 "click"绑定(bind)绑定(bind)复选框会导致意外行为

转载 作者:行者123 更新时间:2023-11-30 11:27:22 25 4
gpt4 key购买 nike

这是我一直在处理的代码。

Javascript:

function ViewModel() {
var self = this;

self.isChecked = ko.observable(false);

self.testing = function(){
console.log("hello from testing");
}
}

var app = new ViewModel();

ko.applyBindings(app);

这是 html:

<div>
<div>
<button data-bind="click: testing" type="button">Something</button>
<input data-bind="checked: isChecked, click: testing" type="checkbox" />
<input data-bind="checked: isChecked" type="checkbox" />
</div>
</div>

我想要完成的是我想要一个复选框,其值通过数据绑定(bind)到我模型中的一个变量并相应地更新。同时,每当用户单击复选框以更改其 bool 值时,我希望在模型中更改值并更新复选框后执行一个函数。

出于测试目的,我将两个按钮数据绑定(bind)到相同的值。当我单击与 click 绑定(bind)到 testing 的复选框时,它的复选标记没有改变,但函数正确执行。但是,单击按钮时,另一个复选框确实会更新以反射(reflect)模型中的更改。

导致此行为的原因是什么,我如何编写更好的解决方案来实现我正在寻找的东西?


编辑:显然,通过向函数添加 return true;,我设法...达到了预期的行为?

function ViewModel() {
var self = this;

self.isChecked = ko.observable(false);

self.testing = function(){
console.log(self.isChecked());
console.log("hello from testing");
console.log(self.isChecked());

return true;
}

}

var app = new ViewModel();

ko.applyBindings(app);

那么问题来了,为什么会这样,安全吗?

最佳答案

这看起来像一个 XY problem .所以,除了@Tomalak 提到的,如果你想在复选框值改变时触发一个函数,你可以 subscribeisChecked 可观察对象

function ViewModel() {
var self = this;

self.isChecked = ko.observable(false);

self.isChecked.subscribe(function(newValue) {
// this gets executed every time "isChecked" changes
console.log(self.isChecked());
console.log(newValue);
});
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="checked: isChecked" type="checkbox" />

使用 subscribe 而不是 click 绑定(bind)的优势在于,即使您像这样以编程方式设置复选框的值时也会触发此函数 self.isChecked(假)

关于javascript - KnockoutJS 使用 "checked"和 "click"绑定(bind)绑定(bind)复选框会导致意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47522616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com