2
votes

I have a master viewModel with two VMs and it is created via mapping plugin.

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

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

Data looks like this:

'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 has observableArray children

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

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

Everything seems to work fine until I update data. Updated data:

'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'
}   

In html first.children().length returns correct length of updated array, foreach.children also works fine, but calLength() function in VM doesn't return updated length. WHY?

It looks like all data updated successfully, but can't be accessed in VM function if it is an array ( i can easily get self.title() or other observable data ). Maybe there are some problems with mappingOptions?

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

Here is a full demo:

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

p.s. If you have any other comments, you are welcome to post them :)

Thank You very much.

1

1 Answers

1
votes

Make sure your children observable array is being updated with new values, and not replaced with a new observable array.