0

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?

2 Answers 2

3

Do it the other way around: http://jsfiddle.net/tQzu2/1/

Knockout updates the UI based on its model, i.e. you're binding the elements to the model and not vice versa.

1
  • I thought of that, but in actual code I was passing off the textbox as a reference to function like $('.fac').click(function(){func(this);}). But a good answer nonetheless.
    – oglester
    Sep 26, 2012 at 14:48
1

This is probably because changing input value via val() method does not fire change event. Try to trigger change event manually after changing input value

$("#btn").click(function(){
    $(".fac").val('val');
    $(".fac").trigger('change');
})

But this may not work if binding trigger set to other value than 'change'.

Example: http://jsfiddle.net/zSmSY/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.