【问题标题】:pureComputed properties using mapping plugin使用映射插件的 pureComputed 属性
【发布时间】:2016-03-11 06:59:45
【问题描述】:

我正在使用 knockoutJS,但在使用 pureComputed 属性时遇到了一些问题。

这是我的模特

var LineItem = function() {
    var self = this;
    self.id = ko.observable('');
    self.name = ko.observable('');
    self.description = ko.observable('');
    self.unit_price = ko.observable('');
    self.quantity = ko.observable(1);
    self.amount = ko.pureComputed(function() {
        return self.unit_price() ? self.unit_price() * self.quantity() : 0;
    });
};

当我使用 ko.mapping.toJS(LineItem) 发布数据时,它可以工作,但是,当我从服务器获取数据(以 json 格式)并使用 ko.mapping.fromJS(dataJSON) 再次构建时视图模型,它加载了数量字段,但它不是一个 pureComputed 值,所以当我更改数量值时它不会更新。

一旦使用 knockoutJS 映射插件从服务器检索字段,我如何才能再次将字段设为 pureComputed?

【问题讨论】:

  • 您是否考虑过使用ignore 映射选项?
  • 不想忽略某个字段,只想保留ko.mapping.toJS之后的pureComputed

标签: javascript knockout.js viewmodel knockout-mapping-plugin


【解决方案1】:

由于金额是 api 数据的一部分,您可以将 pureComputed 与金额分开:

this.amount = ko.observable(0);
this.amountComputed = ko.pureComputed(function() {
        return self.unit_price() ? self.unit_price() * self.quantity() : 0;
    });

如果这对您不起作用,您可以确保在调用 fromJS 后重新创建您的数量 pureComputed。

【讨论】:

  • 我认为这个解决方案不适合我。我需要计算金额。
【解决方案2】:

解决了! 我使用 ko.mapping.fromJS 的第二个参数(映射)来重建我的 LineItem 视图模型,包括计算的数量。我不确定这是否是更好的方法,但它确实有效。

  var LineItem = function(data) {
        var self = this;
        self.id = ko.observable(data.id);
        self.name = ko.observable(data.name);
        self.description = ko.observable(data.description);
        self.unit_price = ko.observable(data.unit_price);
        self.quantity = ko.observable(data.quantity);
        self.amount = ko.pureComputed(function() {
           return self.unit_price() ? self.unit_price() * self.quantity() : 0;
        });
     };



var mapping = {
  'line_items': {
     create: function(options) {
        return new LineItem(options.data);
     }
  }

}

【讨论】:

    【解决方案3】:

    我用这个:

    var unmapped = ko.mapping.toJS(self.Model);
    var unmappedJSON = ko.toJSON(unmapped);
    $.ajax({
        url: 'myUrl',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: unmappedJSON,
        success: function (data, textStatus, jqXHR) {
    
            var ignoreMapping =
            {
                'ignore': ["amount"]
            }
    
    
            ko.mapping.fromJS(data, ignoreMapping, self.Model);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        ...
        }
    });
    

    使用 ignoreMapping 插件会忽略此字段并保持可计算性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2012-09-25
      • 2017-09-25
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多