edit functionality is not working in knockout js

2019-09-18 17:43发布

问题:

I just created an editable using an example available on net.in this when i am trying to edit the grid then it doesn't show the value it shows the input field blank.can any body help ? in edit i am calling this function

  self.editFruit = function (fruit) {
        if (self.editingItem() == null) {
            // start the transaction
            fruit.beginEdit(self.editTransaction);

            // shows the edit fields
            self.editingItem(fruit);
        }
    };

here is fiddle jsfiddle

回答1:

At the time the binding is evaluated for the first time the editValue child observable of each of fruit's observables ( data-bind="value: name.editValue" ) doesn't exist. When you click on the "edit" link the editValue observable is created but knockout doesn't know that it has to rebind.

You can solve this 2 ways.

1 . Create a virtual if binding around each input. When the if becomes true, the content will be reinserted back into the DOM causing the bindings to re-evaluate. Make sure that editValue observable is attached to its parent BEFORE editingItem observable is set, otherwise you are in the same situation

<!-- ko if: $root.isItemEditing($data) -->
<input data-bind="..."></input>
<!-- /ko -->

2 . Make sure that all observables have the editValue observable attached to the parent observable before the model is bound, the set editValue observable's value in the beginEdit fn.

function Fruit(data) {
  var self = this;
  self.name = ko.observable(data.name || "");
  self.name.editValue = ko.observable();

  self.rate = ko.observable(data.rate || "");
  self.rate.editValue = ko.observable();
}

ko.observable.fn.beginEdit = function (transaction) {
  ...

  if (self.slice)
    self.editValue(self.slice());
  else
    self.editValue(self());

  ...
}