1

当我们第一次应用 ViewModel 时一切正常,但是如果我们在创建计算字段后重新应用映射,它们就会被删除。如果我们不更改密钥,这段代码显然可以工作

http://jsbin.com/ojabaf/14/edit

var modelJs = {test:{
  list: [{name: 'a', val: 5, list: [ {name:'b', val: 11}, {name: 'c', val: 13}  ]}]}
};

var mapping = { 
    'list': {
        key: function(data) { return ko.utils.unwrapObservable(data.name); }
    },
  'name': {
    key: function(data) { return ko.utils.unwrapObservable(data.name); }
  }
};

var model = ko.mapping.fromJS(modelJs, mapping);

ko.utils.arrayForEach(model.test.list(), function(item) {
  item.comp = ko.computed({read: function() { return this.val() * 2; }  , owner: item });
  ko.utils.arrayForEach(item.list(), function(item2) {
    item2.comp = ko.computed({read: function() { return this.val() * 3; }  , owner: item2 });  
  });
});

ko.applyBindings(model);

$('button').click(function () {
  var modelJs = {test: {val: 3, list: [{name: 'b', val: 7, list: [ {name:'s', val: 15}, {name: 'c', val: 17} , {name: 'd', val: 17}, {name: 'f', val: 17}]}]}};
  ko.mapping.fromJS(modelJs, model);
});

有没有办法用 ko.mapping 重新计算那些计算字段,而不刷新页面?

我也尝试过使用模板... http://jsbin.com/ojabaf/15/edit

4

1 回答 1

2

与其循环遍历数组并将计算的 observables 添加到每个项目,不如comp设置映射,以便在创建项目时添加它们。

var mapping = {
  'list': {
    key: function (data) {
      return ko.utils.unwrapObservable(data.name);
    },
    create: function (options) {
      var mapped = ko.mapping.fromJS(options.data, {
        'list': {
          key: function (data) {
            return ko.utils.unwrapObservable(data.name);
          },
          create: function (options) {
            var mapped = ko.mapping.fromJS(options.data);
            return ko.utils.extend(mapped, {
              comp: ko.computed(function () {
                return this.val() * 3;
              }, mapped)
            });
          }
        }
      });
      return ko.utils.extend(mapped, {
        comp: ko.computed(function () {
          return this.val() * 2;
        }, mapped)
      });
    }
  },
  'name': {
    key: function (data) {
      return ko.utils.unwrapObservable(data.name);
    }
  }
};
var model = ko.mapping.fromJS(modelJs, mapping);

http://jsbin.com/asomiq/1/edit

于 2012-09-27T16:18:15.967 回答