我是 Knockout 新手,正在努力解决以下问题。
我制作了一些可点击的产品 div(带有隐藏的复选框)。如果有人单击 div,则会选中一个隐藏的复选框,并且样式会发生变化。
现在我想添加依赖项,因为某些产品无法同时订购。我想根据复选框值(真/假)来执行此操作。假设,如果选择产品 1,则应使用附加类“disabledDiv”禁用产品 2 和 3。然而,这个事件更改绑定(bind)器对我来说不起作用。我什至没有发出警报。
self.valueCheckboxChanged = function() {
alert('value has changed')
}
谁能帮帮我,我很迷茫。我做了一个简化的 JSFiddle ( https://jsfiddle.net/Seabiscuito/f1qnr8a2/ ) 来说明这个问题。
最佳答案
修复 1:从复选框中删除value
绑定(bind)。
修复 2:将 hidden
属性添加到复选框,以防止事件冒泡出现任何问题(点击输入将切换值、冒泡到 div 和将其切换回来)
修复 3:订阅复选框的 isChecked
可观察对象,而不是使用 change
事件。例如:
self.checkedProducts = ko.pureComputed(function() {
return this.products().filter(function(p) {
return p.isChecked();
});
}, this);
self.checkedProducts.subscribe(function(checked) {
// Do something with the checked products
}, this);
最后一部分是最复杂的部分。确保您不会陷入无限循环! 如果您解释要创建哪种依赖项,我可以编辑最后一部分以更好地反射(reflect)您的需求。
这是一个通过订阅
显示项目之间关系的示例:
function Cart(products) {
this.products = products.map(Product.fromData);
const main = this.products[0];
const others = this.products.slice(1);
main.isChecked.subscribe((included) => {
const action = included
? Product.disable
: Product.enable;
others.forEach(action);
});
};
function Product(name) {
this.name = name;
this.isChecked = ko.observable(false);
this.enabled = ko.observable(true);
};
Product.prototype.toggle = function() {
if (!this.enabled()) return;
this.isChecked(!this.isChecked());
};
Product.prototype.enable = function() {
this.enabled(true);
};
Product.prototype.disable = function() {
this.enabled(false);
this.isChecked(false);
};
Product.enable = p => p.enable();
Product.disable = p => p.disable();
Product.fromData = name => new Product(name);
ko.applyBindings(new Cart(["Deluxe Lunch", "Drink", "Food"]));
li { opacity: .5; list-style: none; padding: 1em; border-radius: 3px; border: 1px solid black; margin-bottom: .25em; }
.isChecked { background: yellow }
.isEnabled { opacity: 1; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: products">
<li data-bind="click: toggle.bind($data), css: { isChecked: isChecked, isEnabled: enabled }">
<input type="checkbox" data-bind="checked: isChecked" hidden />
<span data-bind="text: name"></span>
</li>
</ul>
关于jquery - Knockout.js:选中一个复选框时禁用其他复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987644/