Search code examples
knockout.jsknockout-mapping-plugin

What's the use of observable array and mapping plugin in Knockoutjs


If my JSON data can be converted directly using ko.observableArray then what's the use of Mapping plugin because as far as I know mapping plugin is used for converting JSON into knockout object. I am new to KO don't know much about it


Solution

  • The elements of an observableArray aren't automatically observable themselves; subscriptions (including bindings) to an observableArray respond to changes to the array itself (such as adding or removing elements) but not to changes to the content of an individual element. If you want the latter to happen, you need to turn the (relevant) properties of each object in the array into observables, and that's what the mapping plugin does for you.

    Consider:

    var vm={};
    vm.dummy=[{num:'one'}, {num:'two'}, {num:'three'}, {num:'four'}];
    // Create observableArray of plain objects
    vm.oa1=ko.observableArray(vm.dummy);
    // Create observableArray of objects with observable properties
    vm.oa2=ko.mapping.fromJS(vm.dummy);
    ko.applyBindings(vm);
    

    Along with:

    <ul data-bind="foreach: oa1"><li data-bind="text: num"></li></ul>
    <ul data-bind="foreach: oa2"><li data-bind="text: num"></li></ul>
    

    Now in the console:

    vm.oa1()[1].num = 'five'
    

    Nothing changes in the display

    vm.oa1()[1].num
    

    five

    vm.oa1()[1].num('five');
    

    Error, because the element isn't an observable

    vm.oa2()[1].num('five');
    

    The second list changes