【问题标题】:knockoutjs data manipulation after update in view model issue在视图模型问题中更新后的 knockoutjs 数据操作
【发布时间】:2013-01-25 21:59:36
【问题描述】:

我有一个带有两个虚拟机的主视图模型,它是通过映射插件创建的。

viewModelObj    = {
    first           : new firstVM(),
    second          : new secondVM()
}

viewModel = mapping.fromJS(viewModelObj, mappingOptions);
ko.applyBindings(viewModel);

数据如下所示:

'firstObj'      : {
    'title'         : 'CURRENT title goes here',
    'children'      : [
        { 'id': '00001', 'name': 'Rube no 1' },
        { 'id': '00002', 'name': 'Rube no 2' },
        { 'id': '00003', 'name': 'Rube no 3' }
    ],
    'warning'   : false
},
'secondObj'     : {
    'title'         : 'Second Item title'
}

firstVM 有 observableArray 子节点

self.children = ko.observableArray(item.children);

self.calLength = ko.computed(function() {
  return 'Total ' + self.children().length;
});

在我更新数据之前,一切似乎都运行良好。更新数据:

'firstObj'  : {
    'title'     : 'UPDATED TITLE goes here',
    'children'  : [
        { 'id': '00004', 'name': 'Rube no 4' },
        { 'id': '00005', 'name': 'Rube no 5' },
        { 'id': '00006', 'name': 'Rube no 6' },
        { 'id': '00007', 'name': 'Rube no 7' },
        { 'id': '00008', 'name': 'Rube no 8' },
        { 'id': '00009', 'name': 'Rube no 9' }
    ],
    'warning'   : true
},
'secondObj'     : {
    'title'         : '2nd Title UPDATED'
}   

在 html 中 first.children().length 返回更新数组的正确长度,foreach.children 也可以正常工作,但是 VM 中的 calLength() 函数不返回更新后的长度。为什么?

看起来所有数据都成功更新了,但是如果它是一个数组,则无法在 VM 函数中访问(我可以轻松获取 self.title() 或其他可观察数据)。也许mappingOptions有一些问题?

'first' : {
    create : function(options) {
        return  mapping.fromJS(options.data, {}, this);
    }
},
'second' : {
    create : function(options) {
        return  mapping.fromJS(options.data, {}, this);
    }
}

这是一个完整的演示:

http://jsfiddle.net/simoncereska/bfvgT/

附言如果你还有其他的cmet,欢迎留言:)

非常感谢。

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    确保您的孩子可观察数组正在更新为新值,而不是被新的可观察数组替换。

    【讨论】:

      猜你喜欢
      • 2013-12-26
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 2021-07-23
      • 2012-03-27
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多