如何将动态复选框值绑定到对象上的Knockout observableArray?

时间:2018-04-28 16:18:42

标签: javascript jquery knockout.js

我已将fiddle发布到此处,对此有评论。

如何将AllCustomers数组转换/映射到另一个Customer对象数组?

我需要将选中的复选框对象推送到self.Customer(),{CustomerType,checked}

然后我将循环遍历Customer对象Array列表并返回所有已检查Customers的数组 - self.CheckedCustomers



function Customer(type, checked)
{
  var self = this;
  
  self.CustomerType = ko.observable(type);
  self.IsChecked = ko.observable(checked || false);
}

function VM()
{
  var self = this;
  
  //dynamically populated - this is for testing puposes
  self.AllCustomers = ko.observableArray([
    { 
      code: "001",
      name:'Customer 1'
    },
    { 
      code: "002",
      name:'Customer 2'
    },
    { 
      code: "003",
      name:'Customer 3'
    },
  ]);
  
 self.selectedCustomers = ko.observableArray([]);
 self.Customer = ko.observableArray([]);
  
//How can I convert the AllCustomers array into an array of Customer object??
//I need to push the checked object in to self.Customer(), {CustomerType,checked}

//uncomment below - just for testing looping through Customer objects
/*
self.Customer = ko.observableArray([  
    new Customer("001"),
    new Customer("002")
  ]);
*/
  
 // This array should return all customers that checked the box
self.CheckedCustomers = ko.computed(function()
{
    var selectedCustomers = [];
    ko.utils.arrayForEach(self.Customer(), function (customer) {
        if(customer.IsChecked())
            selectedCustomers.push(customer);
    });
    return selectedCustomers;
});
}
ko.applyBindings(new VM());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- ko foreach: AllCustomers -->
  <input type="checkbox" data-bind="value: $data.code, checked:$parent.selectedCustomers" /> 
   
  <span data-bind="text: $data.name"></span>
  <!-- /ko -->
<br /> 
  <h4>selectedCustomers code</h4> 
  <div data-bind="foreach: selectedCustomers">
    <span data-bind="text: $data"></span>
  </div>
  
  <h4>Checked boxes are??</h4> 
  <div data-bind="foreach: CheckedCustomers">
    <span data-bind="text: CustomerType"></span>
    <span data-bind="text: IsChecked"></span>
    <span>,</span>
  </div> 

<!-- Use this to loop through list of Customer object Array, uncomment below to test-->
<!-- 
  <!-- ko foreach: Customer --
  <input type="checkbox" data-bind="checked: IsChecked" />
   
  <span data-bind="text: CustomerType"></span>
  <!-- /ko --
-->
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您正在尝试将包含属性codename的对象转换为属性CustomerTypeIsChecked的对象。我假设您在创建新的code对象时希望CustomerType映射到Customer

这是一个工作的jsfiddle或多或少你想要的。

https://jsfiddle.net/s9yd0e7o/10/

添加了以下代码:

self.selectedCustomers.subscribe(function() {
  self.Customer.removeAll();
  ko.utils.arrayForEach(self.selectedCustomers(), function(item) {
      self.Customer.push(new Customer(item, true));
  });
});