繁体   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