Search code examples
knockout.jsknockout-mapping-plugin

Knockout Mapping plugin not working on array of objects


Knockout mapping is not working a array of objects.

Here is my fiddle http://jsfiddle.net/varunfiddle/03rv2the/

Basically I have tried to map a array of objects into a observable array.

var ViewModel = function() {
    var self = this;
    var newData = 
                    [{"PersonId":1,"Name":"LoginUser1","OriginalSource":null,"Remarks":null},
                     {"PersonId":2,"Name":"LoginUser1","OriginalSource":null,"Remarks":null}];

    self.persons=ko.mapping.fromJS(newData, {}, self);

};

var myVM = new ViewModel();
ko.applyBindings(myVM);

And later bind it in the html

<table>
    <tbody data-bind="foreach:persons">
        <tr>
            <td>
                <label data-bind="text:Name"></label>
            </td>
        </tr>
    </tbody>

</table>

I do not see data binding taking place on the array of objects. Is there a fix ? Thanks.


Solution

  • Remove the third argument on your call to ko.mapping.fromJS() (and remove the second one too, you don't need it now). The third parameter is the existing object to add the mapped properties to. You don't want to add that array to your view model like that, you're just trying to create a new array with the mapped properties.

    self.persons = ko.mapping.fromJS(newData);
    

    If you wanted to add to your view model using the mapping plugin, you need to create an object that has the same structure as the view model you wish to create, then pass it in to the function (with the third parameter).

    var ViewModel = function() {
        var self = this;
        var model = {
            persons: [
                {"PersonId":1,"Name":"LoginUser1","OriginalSource":null,"Remarks":null},
                {"PersonId":2,"Name":"LoginUser1","OriginalSource":null,"Remarks":null}
            ]
        };
    
        ko.mapping.fromJS(model, {}, self);
    };