I have a page with a knockout.js model. I am ‘serializing’ the data to a textbox in JSON format by binding a computed property of the serialized object.
Selection of the parts that work:
View Model
function CourseParticipant(name, facility) {
var self = this;
self.name = ko.observable(name);
self.facility = ko.observable(facility);
}
function CourseParticipantViewModel() {
var self = this;
self.participants = ko.observableArray();
self.participants.push(new CourseParticipant("Greg", "init"));
self.addParticipant = function(participant) {
self.participants.push(new CourseParticipant("", ""));
}
self.removeParticipant = function(participant) {
self.participants.remove(participant);
}
self.serializedValue = ko.computed(function() {
return ko.toJSON(self.participants(), null, null);
}, self);
}
ko.applyBindings(new CourseParticipantViewModel());
$("#btn").click(function(){
$(".fac").val('val');
})
HTML
<table class='pc-tbl'>
<tbody data-bind="foreach: participants">
<tr><td colspan='100%'>
<a href="#" data-bind="click: $root.removeParticipant">x</a></td></tr>
<tr>
<th>Name:</th>
<td><input data-bind="value: name" /></td>
</tr>
<tr>
<th>Facility:</th>
<td><input data-bind="value: facility" class='fac' /></td>
</tr>
</tbody>
</table>
<br />
<textarea data-bind="value: serializedValue()" style='width:300px; height:100px;'></textarea>
<a href="#" data-bind="click: addParticipant">Add Participant</a>
<input type=button id='btn' value='test' />
The part I am having trouble with is getting Knockout to detect the change when form is edited via JavaScript. A sample of the issue can be found here:
http://jsfiddle.net/oglester/tQzu2/
The issue is that when you click the test button and it updates the form, the model is not updated. How do I force the form to notify the View Model?
This is probably because changing input value via
val()method does not firechangeevent. Try to triggerchangeevent manually after changing input valueBut this may not work if binding trigger set to other value than ‘change’.
Example: http://jsfiddle.net/zSmSY/