当我将项目添加到observablearray时,我正在努力敲除,并进行UI更新。Intial Listing和DeleteMployee工作正常并更新UI Arpropriatley,但是当我尝试添加员工时,UI根本没有更新。以下是ViewModel和HTML。感谢我能为此获得的任何帮助。
ViewModel:
function viewModel() {
var self = this;
self.employees = ko.observableArray();
self.deleteEmployee = function () {
var employee = this;
dataservice.del(this.id, function () {
self.employees.remove(employee);
})
},
self.addEmployee = function () {
var emp = {};
emp.Name = $("#newName").val();
emp.Email = $("#newEmail").val();
dataservice.add(emp, function (data) {
var employee = new Employee(data.id, emp.Name, emp.Email);
self.employees.push(employee);
});
}.bind(self);
$.each(data.rows, function (index, row) {
self.employees.push(new Employee(row.value.Id, row.value.Name, row.value.Email));
});
return {
employees: self.employees,
deleteEmployee: self.deleteEmployee,
addEmployee: self.addEmployee
}
};
ko.applyBindings(new viewModel());
html
<article data-bind="foreach: employees">
<div class="emp">
<div class="empTop">
<span data-bind="text: name"></span>
<div class="del" data-bind="click: $parent.deleteEmployee, clickBubble: false"></div>
</div>
<div class="empContent">
<div class="row">
<label for="name">Name</label>
<input name="name" type="text" data-bind="value: name">
</div>
<div class="row">
<label for="name">Email</label>
<input name="email" type="text" data-bind="value: email">
</div>
<div class="row">
<input type="button" value="Update">
</div>
</div>
</div>
</article>
<aside>
<h3>Create</h3>
<div>
<div class="row">
<label for="newName">Name</label>
<input id="newName" name="newName" type="text">
</div>
<div class="row">
<label for="newEmail">Email</label>
<input id="newEmail" name="newEmail" type="text">
</div>
<div class="row">
<input type="button" value="Create" data-bind="click: addEmployee">
</div>
</div>
</aside>
看来,问题不在敲除。我将您的代码放入JSFIDDLE中,在JavaScript中评论了几行,但没有触摸您的HTML,创建工作正常。
看小提琴:http://jsfiddle.net/mshmelev/zf5pc/
所以,问题可能是:
-
dataservice.add()
功能未调用您的回调 - 您的
Employee
类有问题(我在小提琴中创建了一个存根)
结果发现渲染的项目,但是,这令人尴尬,我有一些jQuery隐藏了beeing beeing添加了$('。emp')。hide()。这个小错误使我造成了塞弗拉小时的困惑。谢谢您的所有建议。