【问题标题】:Binding on observableArray created from another observableArray绑定从另一个 observableArray 创建的 observableArray
【发布时间】:2017-05-08 23:16:10
【问题描述】:

我有一个从 ajax 调用返回的对象,我想从这个对象做一些计算,这取决于用户的输入。输入是数字输入和复选框,以在计算中包含另一个数字。

我的 JS 是:

var viewModel = function() 
{
        var self = this;
    self.currentVal = ko.observable(2);
    self.includeTax = ko.observable(false);
    self.sales = ko.observableArray([]);
    self.computedSales = ko.observableArray([]);

self.sales([
    {"ProductID": "10121a", "Cost": 110, "Quantity": 6, "X": 9034.25, "Other": 23, "Date": 2017-05-5}, 
    {"ProductID": "10122b", "Cost": 10, "Quantity": 18, "X": 152.99, "Other": 20, "Date": 2017-05-3},
    {"ProductID": "10123c", "Cost": 1000, "Quantity": 2, "X": 99.50, "Other": 5, "Date": 2017-05-1}]);

self.computeSales = function() {
    ko.utils.arrayForEach(self.sales(), function (item) {
    self.computedSales().push({
        "ProductID": item.ProductID, 
      "Total": item.Cost * item.Quantity,
      // "Total" is needed for the Calc value, is there a way to re-use the Total without having to duplicate it below?:
      // "Calc": item.Cost * item.Quantity * (self.currentVal / 100)
      "Calc": self.includeTax() == true ? (item.Cost * item.Quantity * (2 / 100) * .5) : (item.Cost * item.Quantity * 2 / 100)
      });

      //alert(self.computedSales()[self.computedSales().length -1].Total);
  });
  // self.currentVal not correct:
  //alert(self.currentVal);
};
self.computeSales();
};

$(function () {
    ko.applyBindings(new viewModel());
});

当我勾选复选框或更改输入中的值时,Calc 列没有改变 - 我做错了什么?

我的主要目标是找到一种方法来重用某些属性(例如 Total),而不必复制 item.Cost * item.Quantity,但我想这是另一个单独的问题。

Fiddle

任何帮助表示赞赏!

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    我认为,如果您的销售对象实际上是可以附加计算的强类型对象,这会更容易。首先,您应该为您的销售创建一个对象:

    var sale = function(item) {
        var thisSale = this;
        thisSale.productId = ko.observable(item.ProductID);
        thisSale.cost = ko.observable(item.Cost);
        thisSale.quantity = ko.observable(item.Quantity);
        //etc with all properties needed.
        thisSale.calc = ko.pureComputed(function() {
            return self.includeTax() == true ? (thisSale.Cost * thisSale.Quantity * (2 / 100) * .5) : (thisSale.Cost * thisSale.Quantity * 2 / 100)
        });
    }
    

    然后使用您的数据创建这些对象:

    self.computeSales = function() {
        ko.utils.arrayForEach(self.sales(), function (item) {
            self.computedSales().push({
                new sale(item);
            });
        });
    };
    

    每当它引用的可观察对象更新时,计算值都会更新,因此通过将 calc 设为计算值,您应该能够在复选框被更改时更新它。抱歉,如果这不是很清楚并且我根本没有测试过这段代码,所以你可能需要调整它,但一般原则应该在那里!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2013-05-07
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多