Search code examples
asp.net-mvcknockout.jsknockout-mapping-plugin

How KnockoutJS Mapping plugin works


here i got a sample code which said KnockoutJS Mapping plugin automatically bind UI. here is code

<script src="~/Scripts/knockout.mapping-latest.js"></script>
 <script type="text/javascript">
        $(function() {
            var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
            ko.applyBindings(viewModel);
          });
</script> 

suppose my html binding as follows

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

and my server side model return json like

{fname:Josh;lname:Steve};

so here my question is how KnockoutJS Mapping plugin could understand that fname value need to map to databinding firstName & lname need to map to databinding lastName ?

am i clear what i am trying to say. so guide me in this case how one could bind json to html UI through KnockoutJS Mapping plugin.

in this situation KnockoutJS Mapping plugin would be right choice or not ?

do i need to bind manually by viewmode like

First name:

Last name:

json as follows var person = {fname:Josh;lname:Steve};

var viewModel = function(person) {
    this.firstname= ko.observable(person.fname);
    this.lastname= ko.observable(person.lname);
};

ko.applyBindings(new viewModel(person));

Solution

  • As requested in the comment I put this as a possible answer.

    If you have model with many properties and want only some of them to map to different names, this is the way to do it:

    var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
    var extendViewModel = function () {
        this.firstName = ko.computed({
            read: function(){
                return viewModel.fname();
            },
            write: function(value){
                viewModel.fname(value);
            },
            owner: viewModel
        });
    };
    
    viewModel = ko.mapping.fromJS(new extendViewModel(), viewModel);
    ko.applyBindings(viewModel);
    

    Then you can use firstName in your markup for bindings and viewModel.fname will be updated, too.