Search code examples
knockout.jsknockout-mapping-plugin

how to use knockout mapping plugin?


I want to use plugin to populate data, but values are not populated.

Simple example:

var data = {
    Type: 1,
    Id: "123-12321"
};

var RiskItemModel = function (item) {
    var self = this;
    self.Id = ko.observable("tes");
    self.Type = ko.observable(); //enum int


    if (item) {
      // DATA SHOULD BE POPULATED HERE, but no effect
      ko.mapping.fromJS(item, this);
    };
};

var model = new RiskItemModel(data);
ko.applyBindings(model);

// I HAVE TRIED THIS ALSO, NO EFFECT
//ko.mapping.fromJS(data, model);

HTML:

<div>
    <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</div>

JSFidde: http://jsfiddle.net/wLbV6/


Solution

  • You are not using the correct overload of the ko.mapping.fromJS function.

    You need to write:

    ko.mapping.fromJS(item, {} /* mapping options */, this);
    

    Demo JSFiddle.

    ko.mapping.fromJS function only works with supping only two parameters if the second parameter is an object which was already mapped by the plugin so it has the "__ko_mapping__" property.

    You can read more about the different overloads here: Unable to parse bindings js error using ko.mapping.fromJSON with parse exist view model