有人可以帮助解释我正在做的可能的根本错误。我需要能够拥有一个模型,该模型可以对一组对象进行分组,每个对象都有自己的一组绑定。
一个小提琴展示了我如何处理一个只有 1 个块的示例,但最后我想要多个块。
html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"
type="text/javascript"></script>
<div class="productblock">
<div class="product">
<input class="binding" data-bind="value: amount" type="text" value="1">
</div>
<div class="product">
<input class="binding" data-bind="value: amount" type="text" value="2">
</div>
<input class="discount" data-bind="value: discount" value="50">
</div>
</div>
<span id="res" data-bind="text: result">result here </span>
js
function ResultViewModel() {
this.result = ko.computed(function () {
return 1;
});
}
function ProductViewModel(val) {
this.amount = ko.observable(val+1);
this.sum = function () {
return this.amount();
};
}
var products = [];
function ProductBlockViewModel(block) {
$.each($(block).find("div.product"), function (index, element) {
var product = new ProductViewModel($(element).find("input").val());
products.push(product);
ko.applyBindings(product);
});
this.discount = ko.observable(22);
}
var productBlocks = [];
$.each($("div.productblock"), function (index, element) {
console.log("a");
var productBlock = new ProductBlockViewModel(element);
productBlocks.push(productBlock);
ko.applyBindings(productBlock, element);
console.log("asdf");
});
ko.applyBindings(new ResultViewModel()); http://jsfiddle.net/Todilo/DGUKu/2/