gpt4 book ai didi

javascript - 如何将动态复选框值绑定(bind)到对象上的 Knockout observableArray?

转载 作者:行者123 更新时间:2023-12-03 02:00:01 25 4
gpt4 key购买 nike

我已经发布了我的fiddle在这里,有评论。

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

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

然后我将循环遍历 Customer 对象数组列表并返回所有已检查客户的数组 - 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 --
-->

最佳答案

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

这是一个可以或多或少满足您想要的功能的 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));
});
});

关于javascript - 如何将动态复选框值绑定(bind)到对象上的 Knockout observableArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com