Javascript 在knockoutjs 中使用复选框列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6736136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Working with a list of checkboxes in knockoutjs
提问by bomortensen
I'm trying to get my head around Knockout.js and I'm quite stuck when it comes to checkboxes.
我正在尝试了解 Knockout.js,但在复选框方面我很困惑。
Server side I'm populating a set of checkboxes with their corresponding values. Now, when any of the unchecked checkboxes are checked, I need to store it's value in a comma-seperated string. When they're unchecked, the value needs to be deleted from the string.
服务器端我用它们对应的值填充一组复选框。现在,当检查任何未选中的复选框时,我需要将其存储在逗号分隔的字符串中。取消选中它们时,需要从字符串中删除该值。
Have anyone got a hint on how to achieve this with knockoutjs?
有没有人知道如何使用knockoutjs 实现这一目标?
I have the following code so far:
到目前为止,我有以下代码:
ViewModel:
视图模型:
$().ready(function() {
function classPreValue(preValue)
{
return {
preValue : ko.observable(preValue)
}
}
var editOfferViewModel = {
maxNumOfVisitors : ko.observable(""),
goals : ko.observable(""),
description : ko.observable(""),
contact : ko.observable(""),
comments : ko.observable(""),
classPreValues : ko.observableArray([]),
addPreValue : function(element) {
alert($(element).val());
this.classPreValues.push(new classPreValue(element.val()));
}
};
ko.applyBindings(editOfferViewModel);
});
And my checkboxes are populated with a foreach loop:
我的复选框填充了 foreach 循环:
<input data-bind="checked: function() { editOfferViewModel.addPreValue(this) }"
type="checkbox" checked="yes" value='@s'>
@s
</input>
I try to pass the checkbox element as the parameter to my addPreValue()
function, but nothing seems to happen when I check the checkbox?
我尝试将复选框元素作为参数传递给我的addPreValue()
函数,但是当我选中复选框时似乎没有任何反应?
Any help/hints on this is greatly appreciated!
非常感谢您对此的任何帮助/提示!
回答by RP Niemeyer
The checked binding expects to be passed a structure that it can read/write against. This could be a variable, an observable, or a writable dependentObservable.
检查绑定期望传递一个它可以读/写的结构。这可以是一个变量、一个 observable 或一个可写的dependentObservable。
When passed an array or observableArray, the checked binding does know how to add and remove simple values from the array.
当传递一个数组或 observableArray 时,已检查的绑定确实知道如何从数组中添加和删除简单的值。
Here is a sample that also includes a computed observable that contains the array as comma delimited values. http://jsfiddle.net/rniemeyer/Jm2Mh/
这是一个示例,其中还包括一个计算出的 observable,其中包含以逗号分隔的值的数组。 http://jsfiddle.net/rniemeyer/Jm2Mh/
var viewModel = {
choices: ["one", "two", "three", "four", "five"],
selectedChoices: ko.observableArray(["two", "four"])
};
viewModel.selectedChoicesDelimited = ko.computed(function() {
return this.selectedChoices().join(",");
}, viewModel);
ko.applyBindings(viewModel);
HTML:
HTML:
<ul data-bind="template: { name: 'choiceTmpl', foreach: choices, templateOptions: { selections: selectedChoices } }"></ul>
<script id="choiceTmpl" type="text/html">
<li>
<input type="checkbox" data-bind="attr: { value: $data }, checked: $item.selections" />
<span data-bind="text: $data"></span>
</li>
</script>
回答by jwize
Why isn't there a Mutually exclusive checkboxes example Online somewhere
为什么没有在线某处的互斥复选框示例
Since this link came up first whilst I was searching for mutually exclusive checkboxes I will share my answer here. I was banging my head against the wall with all my attempts. By the way, when you handle the click event in a binding in-line knockoutjs it seems to disconnect the bindings(maybe only because I tried to call my resetIllnesses function as defined below) even if you return true from the function. Maybe there is a better way but until then follow my lead.
由于在我搜索互斥复选框时首先出现了此链接,因此我将在此处分享我的答案。我用我所有的努力把我的头撞在墙上。顺便说一下,当您在绑定内嵌的 Knockoutjs 中处理 click 事件时,它似乎断开了绑定(可能只是因为我尝试调用下面定义的 resetIllnesses 函数),即使您从该函数返回 true。也许有更好的方法,但在那之前跟随我的领导。
Here is the type I needed to bind.
这是我需要绑定的类型。
var IllnessType = function (name,title) {
this.Title = ko.observable(title);
this.Name = ko.observable(name);
this.IsSelected = ko.observable(false);
};
The array to bind with.
要绑定的数组。
model.IllnessTypes = ko.observableArray(
[new IllnessType('IsSkinDisorder', 'Skin Disorder'),
new IllnessType('IsRespiratoryProblem', 'Respiratory Problem'),
new IllnessType('IsPoisoning', 'Poisoning'),
new IllnessType('IsHearingLoss', 'Hearing Loss'),
new IllnessType('IsOtherIllness', 'All Other Illness')]
);
The reset illness function to clear them all.
重置疾病功能将它们全部清除。
model.resetIllnesses = function () {
ko.utils.arrayForEach(model.IllnessTypes(), function (type) {
type.IsSelected(false);
});
};
The markup
标记
<ul data-bind="foreach:IllnessTypes,visible: model.IsIllness()">
<li><label data-bind="html: Title"></label></li>
<li><input class="checkgroup2" type="checkbox"
data-bind="attr:{name: Name },checked:IsSelected" /></li>
</ul>
This just doesn't work
这根本行不通
If you have been struggling with trying to call the resetIllness function as I below, you will feel my pain.
如果你一直在努力尝试像我下面那样调用 resetIllness 函数,你会感受到我的痛苦。
<input type='checkbox' data-bind="checked:IsSelected,
click: function() { model.resetIllnesses(); return true; }" />
you have been sharing my pain. Well, it works! when you call it from following example. Notice that there is a class that I added above so that I can add the click function.
你一直在分担我的痛苦。好吧,它有效!当您从以下示例中调用它时。请注意,我在上面添加了一个类,以便我可以添加单击功能。
The script that makes all your problems go away.
让您的所有问题消失的脚本。
<script type="text/javascript">
$(function() {
$(".checkgroup2").on('click', function() {
model.resetIllnesses();
var data = ko.dataFor(this);
data.IsSelected(true);
});
});
</script>
Send info to the server
向服务器发送信息
Also, in my case I had to send the information up to the server differently than the default html format so I changed the inputs a little.
此外,在我的情况下,我必须以不同于默认 html 格式的方式将信息发送到服务器,因此我稍微更改了输入。
<input class="checkgroup2" type="checkbox" data-bind="checked:IsSelected" />
<input type="hidden" data-bind="attr:{name: Name },value:IsSelected" />