Adding Observable Properties To Model After Ko.applyBindings In Knockout.js
Solution 1:
I was able to accomplish this by using cleanNode and then reapplying the bindings.
function Model(){};
var model = new Model();
ko.applyBindings(model);
model.name = ko.observable('john');
var myDiv = $('#myDiv')[0];
ko.cleanNode(myDiv);
ko.applyBindings(model, myDiv);
<div id="myDiv">
<span data-bind="text: name"></span>
</div>
Solution 2:
A possible solution would be binding to a partial view, for example:
<div id="viewOne">
<input data-bind="value: name" />
</div>
<div id="viewTwo">
<input data-bind="value: name" />
</div>
<script type="text/javascript">
var viewModelA = {
name: ko.observable("John")
};
var viewModelB = {
name: ko.observable("Doe")
};
ko.applyBindings(viewModelA, document.getElementById("viewOne"));
ko.applyBindings(viewModelB, document.getElementById("viewTwo"));
</script>
So in your case, after adding the new property, you can do apply bindings again only on the part of the view that requires the new data.
Solution 3:
You would probably need to call ko.applyBindings
again. I'm not sure if it'll work though. If it doesn't, you probably would need to look into the KnockoutJS code to find out what applyBindings
does and then figure ouit the functions you need to call to partially apply on your new binding.
Solution 4:
This is supposed to be able to get the applyBindings function to add just the one div. Currently trying it myself in my own application. Not too much luck so far though. Don't know how it would react in your application.
ko.applyBindings(model, document.getElementById('#yourdiv'));
Calling the applyBindings with just the model to bind it to creates additional bindings on the objects. This is not advised.
function Model(){};
var model = new Model();
model.name = ko.observable('john');
ko.applyBindings(model);
model.street = ko.observable('stationstreet');
ko.applyBindings(model);
The latter would create a single binding on the street object, however a second would be created on the name object.
Solution 5:
There is no need to call ko.applyBindings again. Most probably your binding code is called before your html code. If you move applyBinding to document ready everything will be ok!
For jquery:
$(function () {
ko.applyBindings(viewModel);
});
Post a Comment for "Adding Observable Properties To Model After Ko.applyBindings In Knockout.js"