finnsson
finnsson

Reputation: 4067

Force an applyBinding in knockout.js

I'm using knockout to bind a dom-element to a view-model and everything works great the first time a view-model is applied to the dom-element.

Later on a very similar view-model is applied to the same dom-element but the bindings won't update - probably because knockout believes it is the same view-model as before.

Is there a way to force knockout to apply the new view-model and discard the old view-model?

Upvotes: 1

Views: 3495

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The most common approach is to use the template binding. It would look something like:

<div data-bind="template: { name: 'mainTmpl', data: myData }"></div>


var viewModel = {
    myData: ko.observable(),
}    

Now, you can set myData to your new view model like: viewModel.myData(newData) and the template binding will handle re-rendering your content based on the new data.

Otherwise, you can do something like call: ko.cleanNode(yourRootElement) (or pass document) and then ko.applyBindings(yourNewViewModel) to remove the bindings and apply them to a new view model.

Upvotes: 4

Related Questions