I am using Knockout.js and i am pretty new in this. I created a Example to my problem. Here i am trying to bind the knockout binding to dynamically generated elements. But the binding are not applied properly to dynamically generated elements.
I am trying to synchronize the input text field with label element. So whatever we enter in the input field the same text will reflect in its corresponding label element. Please forgive me if i am not clear with my question and please ask me for clearance. Help me guys ? thanks.
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
Activating Knockout But since the browser doesn't know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel);
In your code you are not using one of the main feature of knockout
- auto-generating html. Instead of using jQuery
to add new row - use knockout foreach
binding with observableArray
. When you add new item to array knockout will automatically generate html markup.
Javascript:
function CourseViewModel(){
var self = this;
self.textValue = ko.observable('');
}
function CeremonyViewModel() {
var self = this;
self.cources = ko.observableArray([new CourseViewModel()]);
self.addCourse = function(){
self.cources.push(new CourseViewModel());
};
}
ko.applyBindings(new CeremonyViewModel());
Html:
<div id="menutab">
<form id="createMForm">
<input type="button" id="createmenu" value="Add menu" data-bind="click: addCourse"/>
<div class="menu">
<table data-bind="foreach: cources" class="ui-widget ui-widget-content" >
<tr>
<td>
<label for="CourseName">CourseName</label>
</td>
<td>
<input type="text" data-bind="value: textValue, valueUpdate:'keyup'" class="CreateCourseName" name="CourseName" />
</td>
</tr>
</table>
</div>
</form>
</div>
<div id="courseoptiontab">
<form id="createCOForm">
<div class="options">
<table data-bind="foreach: cources" class="ui-widget ui-widget-content">
<tr>
<td>
<label class="colabel">Course Name
<span class="forcourse" data-bind="text: textValue"></span>
</label>
</td>
</tr>
</table>
</div>
</form>
<div>
Here is working fiddle: http://jsfiddle.net/vyshniakov/g5vxr/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With