淘汰复杂的viewmodel问题

时间:2013-01-09 14:05:17

标签: knockout.js

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

一个小提示显示了我只用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/

1 个答案:

答案 0 :(得分: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);