Knockout列表没有更新模型更新

时间:2014-02-17 04:34:30

标签: knockout.js

数据模型:

var people = [
   {
    personName: {
      first: "Fred",
      last: "Flintstone"
    },
    phones: [{
      use: "home",
      phoneNumber: "555-555-1212"
    }],
    emails: [{
      use: "work",
      emailAddress: "fred@example.com"
    }]
  },

   {
    personName: {
      first: "Barney",
      last: "Rubble"
    },
    phones: [{
      use: "home",
      phoneNumber: "555-444-2323"
    }],
    emails: [{
      use: "work",
      emailAddress: "barney@example.com"
    }]
  }
];

淘汰赛:

var ContactModel = function(contact) {
    var self = this;

    self.updateModel = function(newcontact) {
        self.personName(newcontact.personName);
        self.emails(newcontact.emails);
        self.phones(newcontact.phones);
    };

    self.personName = ko.observable(contact.personName);
    self.emails = ko.observableArray(contact.emails);
    self.phones = ko.observableArray(contact.phones);

    self.addPhone = function(contact) {
        contact.phones.push({
            use: "",
            phoneNumber: ""
        });
    };

    self.removePhone = function(phone) {
        self.phones.remove(phone);
    };

    self.addEmail = function(contact) {
        contact.emails.push({
            use: "",
            emailAddress: ""
        });
    };

    self.removeEmail = function(email) {
        self.emails.remove(email);
    };
};

var PeopleModel = function(people) {
    var self = this;
    self.contacts = ko.observableArray(ko.utils.arrayMap(people, function(contact) {
        return new ContactModel(contact);
    }));

}

DOM:

<table id="contactPanelContent">
    // single form edit here, works fine, console shows updated people
</table>

<table id="contactList">
  <tbody>
    <!-- ko foreach: contacts -->
    <tr>
      <td data-bind="text: $index"></td>
      <!-- ko with: personName -->
      <td data-bind="text: first"></td> 
      <td data-bind="text: last"></td>
      <!-- /ko -->
      <td>
      <!-- ko foreach: phones -->
        <div data-bind="text: phoneNumber"></div>
      <!-- /ko -->
      </td>
      <td>
      <!-- ko foreach: emails -->
        <div data-bind="text: emailAddress"></div>
      <!-- /ko -->
      </td>
    </tr>
    <!-- /ko -->
  </tbody>
</table>

JS:

bound = new ContactModel(newPerson);
contacts = new PeopleModel(people);
ko.applyBindings(bound, document.getElementById("contactPanelContent"));
ko.applyBindings(contacts, document.getElementById("contactList"));

联系表格正常。控制台向人们展示新值。该表格由一个人提供,编辑反映在人们身上。人们也在#contactList中使用,如上所示。该列表只呈现一次,并不反映人们的变化。

请参阅:http://plnkr.co/edit/SbIDkG

0 个答案:

没有答案