當我將項目添加到observableArray時,我正忙於淘汰賽並獲取用戶界面。初始列表和deleteEmployee工作正常,更新UI appropriatley,但是當我嘗試添加一個員工時,UI根本不會更新。下面是viewmodel和html。感謝任何幫助,我可以得到這一點。
視圖模型:淘汰賽推送不更新圖形用戶界面
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>
btw。我沒有得到任何錯誤或類似的東西。我遇到的唯一問題是UI未更新。如果我在添加員工後刷新頁面,它會正確顯示在列表中 – limlim
在我看來,dataservice.add不會調用回調函數。你嘗試調試它嗎?是self.employees.push(員工);函數調用? –
是self.employees.push(員工);被調用並且員工對象支持正確的數據。 – limlim