YMC
YMC

Reputation: 5462

How to make knockout binding work for dynamically added nested objects?

I wonder how to make knockout binding work for dynamically added nested objects. The following sample demostrates what I mean, it does not show "inner value" as I click 'Init inner' button:

<div data-bind="with: InnerObj">
    <div data-bind="text: Pr"></div>
</div>

<button data-bind="click: initInner">Init inner</button>

<script type="text/javascript" language="javascript">
var obj = { 
   InnerObj: null,
   initInner: function () { 
         this.InnerObj = { Pr: "inner value" };
   }
 }

$(function () {        
    ko.applyBindings(ko.mapping.fromJS(obj));
});    

</script>

Upvotes: 0

Views: 1798

Answers (2)

YMC
YMC

Reputation: 5462

This is a slightly modified example of what @Victor Eloy proposed. In the case obj is a pure model taken from server w/o any observables. The trick is to map it to ko.observable(null) which KO mapping does not do by default unfortunately.

<button data-bind="click: initInner">Init inner</button>

<div data-bind="with: InnerObj"> 
    <div data-bind="text: Pr"></div>
</div>

<script type="text/javascript" language="javascript">

var obj = {
    // This case works too: InnerObj: { Pr: "init value"},
    InnerObj: null,

    initInner: function () {
        this.InnerObj({ Pr: ko.observable("new value") });
    }
};

var mapping = {
    'InnerObj': {
        update: function (options) {
            return (options.data == null) ? null : ko.observable(options.data);
        }
    }
};

$(function () {
    var viewModel = ko.mapping.fromJS(obj, mapping);
    ko.applyBindings(viewModel);
});

Upvotes: 0

You should declare this object as an observable and set its value accessing it as a function

<button data-bind="click: initInner">Init inner</button>
<div data-bind="with: InnerObj">
   <span data-bind="text: Pr"/>
</div>

<script type="text/javascript" language="javascript">
var obj = { 
   InnerObj:  ko.observable(),
   initInner: function () {   
      this.InnerObj({'Pr':ko.observable('Inner value')});
   }
}


$(function () {        
    ko.applyBindings(obj);
});    

</script>

key points:1 - InnerObj: ko.observable() 2 - this.InnerObj({'Pr':ko.observable('Inner value')});

references:http://knockoutjs.com/documentation/observables.html - Updating view model from object not working

Upvotes: 1

Related Questions