我有这个视图模型:
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());
};
我在控制台中得到空值,但我正在编辑的项目显示了我的最新更改!!?:(
如果您希望看到更多片段:
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>