ThierryMichel
ThierryMichel

Reputation: 487

Using ko.applyBindingsToNode

In this fiddle https://jsfiddle.net/8279akmL/11/, I am trying to bind the 'test' element to a variable called currentPlacewhich is an observable in my ViewModel. I am using the following knockout statement:

ko.applyBindingsToNode(document.getElementById("test"),{text: currentPlace().name});

However, the div gets bound to the list item locations[0] - the item to which currentPlace is pointing to at the time of binding - instead of currentPlace itself.

When I update currentPlace to point to a different list item locations[1], the div is not updated.

The div only updates when i change the value of locations[0], in the example, I change it to 'FOOBAR'.

How can I bind the 'div' to currentPlace instead of locations[0].

Upvotes: 2

Views: 6093

Answers (1)

Michael Best
Michael Best

Reputation: 16688

In order for Knockout to be able to update the binding, it needs to know which observables to watch. In your code, you're just passing the name observable to the binding. It doesn't know about the currentPlace observable since it was unwrapped before calling ko.applyBindingsToNode. Your code is equivalent to:

var theObservable = currentPlace().name;
ko.applyBindingsToNode(document.getElementById("test"), {text: theObservable});

There are two options to fix this: 1) create a pureComputed that returns the correct name, or 2) use ko.applyBindingAccessorsToNode to pass the entire logic of getting the name to Knockout. Here is your example updated to use the latter approach:

ko.applyBindingAccessorsToNode(
    document.getElementById("test"), 
    { text: function() {return currentPlace().name} });

https://jsfiddle.net/8279akmL/12/

Upvotes: 7

Related Questions