Binding to the View Model existing DOM elements it's extremely easy.
Let's imagine we want to track if a checkbox is checked we would have an input of type checkbox that would look like this
<input type='checkbox'
id='checkbox0'
data-bind='attr: { value: "0" }, checked: $root.checked'>
and a view model like
var viewModel = {
checked: ko.observableArray()
};
in this way we are binding the checked action to the view model, but how does it work for new elements? How can we bind html elements from an MVC partial view? How can we bind these to an existing view model?
Fortunately KnockoutJs has a function 'applyBindings' which allows to do that.
ko.applyBindings(viewModel, idOfTheElementToBind);
To demonstrate this I've created a simple Html page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'>
</script>
<script src="http://gigawebsolution.com/scripts/knockout-2.1.0.js"
type="text/javascript">
</script>
<script type="text/javascript">
var count = 0;
var viewModel = {
checked: ko.observableArray()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
});
function AddAnotherCheckbox(){
var id = "checkbox" + count;
var checkbox = count +
" <input type='checkbox'
id='" + id + "'
data-bind='attr: { value: \"" + count + "\" },
checked: $root.checked'/>
<br/>";
$("#container").append(checkbox);
count++;
$(document).ready(function() {
ko.applyBindings(viewModel, document.getElementById(id));
});
}
</script>
</head>
<body>
<input type="button" onclick="AddAnotherCheckbox()"/>
<div id="container"></div>
<br/>
<br/>
<br/>
Checked : <span data-bind="text: checked"></span>
</body>
</html>