简体   繁体   English

使用ko.mapping.fromJS时,不会触发kn​​ockout subscribe回调

[英]knockout subscribe callback not fired when using ko.mapping.fromJS

I have a question about knockout ko.mapping.fromJS . 我有一个关于knockout ko.mapping.fromJS的问题。 I know that ko.mapping.fromJS is nothing but make all properties observable. 我知道ko.mapping.fromJS只是让所有属性都可以观察到。 However, when I change the value of the input field. 但是,当我更改输入字段的值时。 Even the value is changed as showed, but the subscribe callback never fired. 即使值如所示更改,但订阅回调从未触发。 Can anyone help me, please? 有人可以帮帮我吗? The code snippet in JSFiddle . JSFiddle中的代码片段。

html: HTML:

<tbody>
  <!-- ko foreach: notes -->
  <tr>
    <td class="col-xs-12">
      <p data-bind="text: value"></p>
      <input type="text" class="form-control" data-bind="value: value" />
    </td>
  </tr>
  <!-- /ko -->
</tbody>
<p data-bind="text: show"></p>

js: JS:

var notes = [
   {
     "key": "Field1",
     "value": "Progress"
   },
   {
     "key": "Field2",
     "value": "Plan"
   }
];

function NotesModel() {
  var self = this;
  self.notes = ko.mapping.fromJS(notes, {}, self.notes);
  self.show = ko.observable('');
};

var notesModel = new NotesModel();
ko.applyBindings(notesModel);

notesModel.notes.subscribe(function(newValue) {
   notesModel.show(JSON.stringify(newValue));
}.bind(notesModel));

Bindrid is correct. Bindrid是对的。 notes is an array and the array hasn't changed so there's no reason your subscription would get triggered. notes是一个数组,数组没有更改,所以没有理由你的订阅会被触发。 If you push a new value to the notes array then the event triggers. 如果将新值推送到notes数组,则会触发事件。 You'll have to subscribe to each value individually or make a computed that reads the values of each element and then subscribe to that computed. 您必须单独订阅每个值,或者生成一个读取每个元素的值的计算,然后订阅计算的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM