knockout将selectedItem设置为null

时间:2012-11-09 15:26:02

标签: javascript mvvm knockout.js

我有这个视图模型:

var contactsViewModel = {
      contacts: ko.mapping.fromJS([])                                
};

它会像这样填充:

ko.mapping.fromJS(contactsData, dataMappingOptions, contactsViewModel.contacts);    
ko.applyBindings(contactsViewModel);

映射来自contactItem模型

var dataMappingOptions = {
     key: function (data) {
        return data.id;
     },
     create: function (options) {
         return new contactItem(options.data);
    }
};

现在我有一个selectedItem方法,我将其添加到视图模型中:

contactsViewModel.selectedItem = ko.observable();

所以我可以添加,删除,编辑等。但是当我打电话时取消:

contactsViewModel.cancel = function () {
    contactsViewModel.selectedItem(null);
    console.log(contactsViewModel.selectedItem());
};

我在控制台中得到null但是我正在编辑的项目显示了我的最新更改!! :(

如果您希望查看更多摘要:

var contactItem = function (data) {
     var self = this;
     self.id = ko.observable(data.id);
     self.email = ko.observable(data.email);
     self.firstName = ko.observable(data.firstName);
     self.lastName = ko.observable(data.lastName);
     self.company = ko.observable(data.company);              
     self.reportsURL = ko.computed(function () {
          return "#/reports/contact/" + self.id;
     });
     // validations:
    ko.validation.configure({
          insertMessages : false
    });
    self.email.extend({
          required: true,
          email: true
    });
    self.firstName.extend({ required: true });
    self.lastName.extend({ required: true });
    self.company.extend({ required: true });
    self.errors = ko.validation.group(self);
};

和我的编辑方法:

contactsViewModel.edit = function (contact) {
    contactsViewModel.selectedItem(contact);
};

以及取消该模板的模板:

<script type="text/html" id="edit">
        <td class="editMode">
            <input class="span3 animated fadeInDown" data-bind="value: email, validationAlert : email " />
        </td>
        <td class="editMode">
            <input class="span2 animated fadeInDown" data-bind="value: firstName, validationAlert : firstName " />
        </td>
        <td class="editMode">
            <input class="span2 animated fadeInDown" data-bind="value: lastName, validationAlert : lastName " />
        </td>
        <td class="editMode">
            <input class="span2 animated fadeInDown" data-bind="value: company, validationAlert : company " />
        </td>
        <td class="editMode">
            <ul class="rowOptions">
                <li><a href="#" data-bind="click: $parent.save" title="Save your edits">Save<i class="icon-ok"></i></a></li>
                <li><a href="#" data-bind="click: $parent.cancel" title="Cancel editing">Cancel<i class="icon-remove-circle"></i></a></li>
            </ul>
        </td>
</script>

1 个答案:

答案 0 :(得分:1)

设置selectedItem时,您将其设置为对象的引用。因此,当您进行编辑时,它们将被用于实际对象。