1

有人可以帮助解释我正在做的可能的根本错误。我需要能够拥有一个模型,该模型可以对一组对象进行分组,每个对象都有自己的一组绑定。

一个小提琴展示了我如何处理一个只有 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/

4

1 回答 1

1

见演示:http: //jsfiddle.net/DGUKu/7/

我将重新构建您的代码以使其更清晰。

HTML:

<!-- ko foreach: productBlocks -->
<div class="productblock">
   <!-- ko foreach: productLines -->
  <div class="product">
    <input class="binding" data-bind="value: amount" type="text">
  </div>
  <!-- /ko -->
  <input class="r" data-bind="value: discount" value="50">
</div>
    <hr/>
<!-- /ko -->

<div>
<span id="res" data-bind="text: result"></span>
</div>

JS:

function ProductModel (){
  this.amount = ko.observable(0);
  this.sum = function () {
    return this.amount();
  };
}

// product block contains multiple product line
function ProductBlockViewModel(productArray) {
  this.productLines = ko.observableArray(productArray);
  this.discount = ko.observable(50);
}

// your viewmodel for binding data
// should call applybindings only one
function ViewModel(){
  this.result = ko.observable(0);
  this.productBlocks = ko.observableArray([]);
}

var viewModel = new ViewModel();

// let assume you have 2 blocks:

// block 2 products
viewModel.productBlocks.push(new ProductBlockViewModel([
  new ProductModel(), new ProductModel()
]));

// block 3 products
viewModel.productBlocks.push(new ProductBlockViewModel([
  new ProductModel(), new ProductModel(), new ProductModel()
]));

// you can calculate your total result here
viewModel.result(100);

ko.applyBindings(viewModel);
于 2013-01-09T14:49:13.727 回答