使用knockoutjs中的复选框列表

bom*_*sen 10 html javascript checkbox mvvm knockout.js

我试图了解Knockout.js并且在复选框方面我很困惑.

服务器端我正在填充一组带有相应值的复选框.现在,当选中任何未选中的复选框时,我需要将其值存储在逗号分隔的字符串中.取消选中它们时,需要从字符串中删除该值.

有没人知道如何用knockoutjs实现这个目标?

到目前为止,我有以下代码:

视图模型:

$().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);
});
Run Code Online (Sandbox Code Playgroud)

我的复选框填充了foreach循环:

<input data-bind="checked: function() { editOfferViewModel.addPreValue(this) }"
       type="checkbox" checked="yes" value='@s'>
    @s
</input>
Run Code Online (Sandbox Code Playgroud)

我尝试将checkbox元素作为参数传递给我的addPreValue()函数,但是当我选中复选框时似乎没有发生任何事情?

任何帮助/提示都非常感谢!

RP *_*yer 20

检查的绑定期望传递一个可以读/写的结构.这可以是变量,可观察或可写的dependentObservable.

传递数组或observableArray时,检查的绑定确实知道如何从数组中添加和删除简单值.

下面是一个示例,它还包含一个计算的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);
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

  • 这样就足够了:http://jsfiddle.net/rniemeyer/GErdL/还是你的场景中有更复杂的东西? (2认同)
  • 好的 - 开箱即用,Knockout不会根据当前状态设置值.相反,它将使用视图模型所说的任何内容来确定状态应该是什么.但是,很容易编写一个"包装器"绑定到已检查的绑定,它将为您执行此初始化.这是一个更接近您的服务器输出的示例:http://jsfiddle.net/rniemeyer/vgBUf/.`checkedWithInit`绑定将执行`checked`绑定所做的所有操作,但也会确保该值也被初始化. (2认同)