簡體   English   中英

如何從另一個視圖模型計算一個knockout observableArray?

[英]How to compute a knockout observableArray from another viewmodel?

我正在學習淘汰賽,所以請耐心等待......

拿這個代碼:

HTML:

<div id="itemsContainer">
</div>
<div id="cartContainer">
  <label data-bind="text: totals"></label>
</div>
<div id="items"></div>

Javacript:

function ItemsViewModel() {
  var self = this;
  self.items = ko.observableArray().publishOn("items");
  self.items.push({
    count: 2,
    price: 100
  });
  self.items.push({
    count: 3,
    price: 200
  });
}

function CartViewModel() {
  var self = this;
  self.totals = ko.computed(function() {
    var total = 0;
    $.each(self, function(i, m) {
      total = total + (m.count * m.price);
    });
    return total;
  }, this).subscribeTo("items", true);

}

var itemsVM;
var cartVM;

itemsVM = new ItemsViewModel();
ko.applyBindings(itemsVM, document.getElementById("itemsContainer"));

cartVM = new CartViewModel();
ko.applyBindings(cartVM, document.getElementById("cartContainer"));

小提琴

我想根據我在ItemsViewModel.items中放入(或更改)的數據來更新“總計”。

我現在被困住了,不知道如何讓它發揮作用?

我不確定subscribeTo適用於您嘗試過的計算機...快速解決方法是在CartViewModel構造函數中創建一個(私有)鏡像並在computed使用它:

function CartViewModel() {
  var self = this;

  var allItems = ko.observableArray([]).subscribeTo("items", true);

  self.totals = ko.computed(function() {
    return allItems().reduce(function(total, m) {
      return total + (m.count * m.price);
      }, 0);
  });
}

注意:我已用Array.prototype.reduce替換了$.each ;)


編輯:我在文檔中找到了另一個答案:你可以使用轉換函數:

function CartViewModel() {
  var self = this;

  self.totals = ko.observableArray([])
    .subscribeTo("items", true, function(items) {
      return items.reduce(function(total, m) {
       return total + (m.count * m.price);
    }, 0);
  });
};

用鏡像方法更新了小提琴: http//jsfiddle.net/qzLkjLL1/

用變換方法更新了小提琴: http//jsfiddle.net/ynoc6hha/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM