我在Knockout中使用嵌套的observable数组动态创建表单字段集。我希望能够进行"分配"可观察的字段,以便我可以添加用户数据,并确保它不超过100%。在这里看我的JS小提琴:
JS:
var initialData = [
/* Sample data
{ prodName: "MSVR", splits: [
{ page: "Page Name", allocation: "10%"},
{ page: "Page Name", allocation: "20%"}]
}*/
];
var ProductsModel = function(products) {
var self = this;
self.mmAllPages = ko.observableArray(['Page 1', 'Page 2', 'Page 3']);
self.mmProductList = ko.observableArray(['Product 1', 'Product 2', 'Product 3', 'Product 4']);
self.selectedProduct = ko.observable();
self.prodAllocation = ko.observable();
self.products = ko.observableArray(ko.utils.arrayMap(products, function(contact) {
return { prodName: contact.prodName, splits: ko.observableArray(contact.splits) };
}));
self.addProduct = function() {
currentProduct = self.selectedProduct();
self.products.push({
prodName: currentProduct,
splits: ko.observableArray()
});
self.mmProductList.remove(currentProduct);
};
self.removeProduct = function(contact) {
self.products.remove(contact);
self.mmProductList.push(currentProduct);
};
self.addDefinition = function(contact) {
contact.splits.push({
page: self.mmAllPages(),
allocation: self.prodAllocation(),
});
};
self.removeDefinition = function(phone) {
$.each(self.products(), function() { this.splits.remove(phone) })
};
self.productPercent = function(products){
};
现在,当我将分配字段的值设置为prodAllocation observable时,所有后续分配字段都将使用该值进行更新。我不确定如何使这些字段可以独立观察。
答案 0 :(得分:1)
如果我了解您要去的地方,您的代码会出现一些问题:
$root.prodAllocation
而不是allocation
$root.prodAllocation
对于2.,您可以将addDefinition替换为:
self.addDefinition = function(contact) {
var s = {
page: self.mmAllPages(),
allocation: ko.observable(),
};
s.allocation.subscribe(function () {
var sum = 0;
for (var i = 0; i < contact.splits().length; i++)
sum += contact.splits()[i].allocation() *1;
self.prodAllocation(sum);
});
contact.splits.push(s);
};