Question

Background

I have a single view model, and two models. For each model, I'm attempting to bind a name property to the dom. There are default values for each name, but I want the user to be able to edit these values. Following the Knockout documentation, I went with the hasFocus method. My problem is that, on click, I can edit, but when I click out, the focus does not change, and my array does not update. It looks like my model editable property is never set back to false. See the corresponding HTML and JS below.

So what am I doing wrong? Here's the checklist I was using (to no avail) for troubleshooting...

  1. Ensure that names are observable.
  2. Ensure that editing is observable.
  3. Ensure that my edit function sets editing to true.
  4. Ensure that editing defaults to false
  5. Ensure that <input> has a value binding.
  6. Ensure that <i> has a text binding.
  7. Ensure that that event handlers are bound to the value of editing

JSBin: http://jsbin.com/fehoq/117/edit

JS

function StudentModel(fullName) {
    var _this = this;
    this.fullName = ko.observable(fullName);
    this.editing = ko.observable(false);
    this.edit = function() { 
        _this.editing(true); 
        console.log(_this.editing());
    }; 
    ...
}

HTML

<tbody>
  <!-- ko foreach: students -->
    <tr>
        <td>
          <input data-bind="value: fullName()  + ' ' + ($index() + 1), visible: editing(), hasFocus: editing()"/>
          <i data-bind="visible: !editing(), text: fullName() + ' ' + ($index() + 1), click: edit">&nbsp;</i>
        </td>  
...

       
Was it helpful?

Solution

You would want to bind hasFocus against the observable itself, so that the false value can get written back to it. So, you would want:

hasFocus: editing rather than hasFocus: editing()

In the latter, the binding only receives the value and has no way to get back to the observable to write to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top