How To Get This Simple One-way Binding With Knockout To Work?
I am learning knockout and this is my first ever example of it, so please be gentle. I just want a one-way binding from the model to the textboxes, i.e, whatever is in the model mu
Solution 1:
If you don't pass rootElement
to apply bindings, it's going to use window.document.body
. However, if you script is loaded in head
section, the body
is not available at that moment. So you need to move your 1.js
loading inside the body like this:
<html>
<head>
<meta charset="utf-8"/>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js'></script>
</head>
<body>
<form id = "frm" name = "frm">
<fieldset>
<legend>Your friend's basic information</legend>
<div>
<label for = "FirstName">First Name</label>
<input type = "text" name = "FirstName" id = "txtFirstName" data-bind = "value: friend.firstName" />
</div>
<div>
<label for = "LastName">Last Name</label>
<input type = "text" name = "LastName" id = "txtLastName" data-bind = "value: friend.lastName" />
</div>
</fieldset>
</form>
<script type='text/javascript' src='1.js'></script>
</body>
</html>
Solution 2:
You will need to use mapping library to do that. When you use nested properties like a class you need to use mapping. check it out: Plugin Knockout Mapping
Your code wil be some like that:
var viewModel = function () {
var _vm = null,
init = function () {
_vm = {
friend : ko.mapping.fromJS({
firstName : 'Sathyaish',
lastName : 'Chakravarthy'
}),
change: function(){
_vm.friend.firstName('first name changed');
}
};
ko.applyBindings(_vm, $('#frm').get(0));
}
return {
init: init
}
}();
i have that scenario all the time. I put in JSFIDDLE check it out
Post a Comment for "How To Get This Simple One-way Binding With Knockout To Work?"