选中复选框后获取正确的数据

时间:2016-09-03 13:03:16

标签: javascript knockout.js

我的观点模型:

mat histreal; //data I want to save.
histreal.save("histname.dat", raw_ascii); //saved where my project is

和我的模特:

  function AddEmployeesViewModel() {
    var self=this;
    self.names=ko.observableArray();
  } 

  AddEmployeesViewModel.prototype.addEmployee=function(){
     ???
  };

$.getJSON('/xxx.json').then(function(data){   
        addEmployeesViewModel.names([]);
        for (i=0; i<data.length; i++)  {
          addEmployeesViewModel.names.push({id:data[i].id,name:data[i].name});
        } 
      },
        function(){
          console.log('failure');
        }
     );


var addEmployeesViewModel=new AddEmployeesViewModel();
ko.applyBindings(addEmployeesViewModel);  

我的问题是让addEmployee函数在每次选中复选框时返回与名称对应的 ID。哪种方法最好?

1 个答案:

答案 0 :(得分:0)

checked binding不接受回调,它需要一个observable,根据复选框的状态,它将设置为true或false。

根据您的描述,您似乎希望在复选框上处理click,如果选中,则对相关数据项执行某些操作。

vm = {
  addEmployee: function(data, event) {
    if (event.target.checked) {
      console.debug("Do something with", data.id);
    }
    return true;
  },
  names: ko.observableArray([{
    name: 'one',
    id: 1
  }, {
    name: 'two',
    id: 2
  }])
};

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
  <!-- ko foreach: names -->
  <div>
    <input type="checkbox" data-bind="click: $root.addEmployee"><span data-bind="text: name"></span>
  </div>
  <!-- /ko -->
</div>