我有一个使用敲除实现的 n 级复选框树,其中父级 chechbox 的选择应选择其子级(但不是相反),一旦提交数据,所选元素的 id 应转换为 JSON 发送到服务器。
我无法弄清楚如何单向复选框关系,也无法弄清楚如何以以下方式过滤我的最终 json:
如果选择了一个父级(因为这意味着它的所有子级也被选中),则不在 json 中发送其子级 ID
当只选择一个或几个孩子时如何不发送父母 ID。
列表项的模型是:
marketingListsItem = function (data, parent) {
var self = this;
self.Name = ko.observable(data.Name);
self.Selected = ko.observable(data.Selected);
self.Parent = ko.observable(parent);
self.Children = ko.observableArray([]);
self.Id = ko.observable(data.Id);
self.DateAdded = ko.observable(new Date(data.DateAdded));
self.DateModified = ko.observable(data.DateModified);
if (data.Children) {
ko.utils.arrayForEach(data.Children, function (child) {
self.Children.push(new marketingListsItem(child, this));
}.bind(this));
};
}
这是视图模型部分:
marketingListsViewModel = {
marketingLists: mapping.fromJS([]),
originatorConnectionName: ko.observable(''),
selectedMarketingListIds: ko.observableArray([])
},
init = function (connectionId, connectionName) {
marketingListsViewModel.originatorConnectionName(connectionName);
marketingListsViewModel.getFieldMapping = function () {
require(['mods/fieldmapping'], function (fieldmapping) {
fieldmapping.init(connectionId, connectionName);
});
};
// Here I only managed to filter the parent level selections
marketingListsViewModel.selectedLists = ko.computed(function () {
return ko.utils.arrayFilter(marketingListsViewModel.marketingLists(), function (item) {
return item.Selected() == true;
});
});
marketingListsViewModel.saveMarketingListChanges = function () {
// Which I can filter my JSON to include them but the children are missing
var latestMarketingListChanges = ko.toJSON(marketingListsViewModel.selectedLists, ["Id"]);
console.log(latestMarketingListChanges);
amplify.request("updateExistingMarketingLists", { cid: connectionId, ResponseEntity: { "id": connectionId, "selectedMarketListIds": latestMarketingListChanges } },
function (data) {
console.log(data);
});
}
amplify.request("getExistingMarketingLists", { cid: connectionId }, function (data) {
showMarketingLists();
mapping.fromJS(data.ResponseEntity, dataMappingOptions, marketingListsViewModel.marketingLists);
ko.applyBindings(marketingListsViewModel, $('#marketingLists')[0]);
});
};
最后是视图:
<div id="marketingListsContainer">
<ul data-bind="template: {name: 'itemTmpl' , foreach: marketingLists}"></ul>
<script id="itemTmpl" type="text/html">
<li>
<label><input type="checkbox" data-bind="checked: Selected" /><span data-bind='text: Name'></span></label>
<ul data-bind="template: { name: 'itemTmpl', foreach: Children }" class="childList"></ul>
</script>
</div>
<a class="s_button modalClose right" href="#"><span data-bind="click: saveMarketingListChanges">Save and close</span></a><br>