【发布时间】:2014-04-09 04:48:18
【问题描述】:
如何在 UI 部分更新淘汰赛 js observablearray。最初我正在编辑一个项目,在更新功能中我试图更新一个特定项目,所以我将当前项目对象发送到服务并获取更新的 vales 作为响应。在响应中,我也需要更新 observablearray 以及 UI。我已经尝试过这样的事情,但它对我不起作用...请签入http://jsfiddle.net/up8rB/20/
<div data-bind="ifnot: Role()">
<label for="description">Description</label>
<input type="text" data-bind="value: Description" class="form-control" placeholder="Enter the description..." />
<button data-bind="click: $root.create"> Create</button>
</div>
<div data-bind="if: Role">
<label for="description">Description</label>
<input type="text" data-bind="value: Role().Description" class="form-control" placeholder="Enter the description..." />
<button data-bind="click: $root.update"> Save</button>
</div>
<table id="example1" class="table table-bordered table-striped" data-bind="visible: Roles().length > 0">
<thead>
<tr>
<th>RoleID</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody data-bind="foreach: Roles">
<tr>
<td data-bind="text: $data.RoleID"></td>
<td data-bind="text: $data.Description"></td>
<td>
<button data-bind="click: $root.edit" >Edit</button>
<button data-bind="click: $root.delete" >Delete</button>
</td>
</tr>
</tbody>
</table>
function RoleViewModel() {
var self = this;
self.RoleID = ko.observable("0");
self.Description = ko.observable().extend({
required: { message: 'Please supply description ..' }
});
var Role = {
RoleID: self.RoleID,
Description: self.Description
};
self.Role = ko.observable();
self.Roles = ko.observableArray();
$.ajax({
url: 'Service.svc/RoleCollection',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Roles(data); //Put the response in ObservableArray
}
});
self.edit = function (Role) {
self.Role(Role);
}
self.update = function () {
var Role = self.Role();
$.ajax({
url: '..service.svc/UpdateRole',
cache: false,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Role),
success: function (data) {
for (var i = 0; i < self.Roles().length; i++) {
alert(self.Roles()[i].RoleID());
if (self.Roles()[i].RoleID() === data.RoleID) {
self.Role(self.Roles()[i]);
break;
}
}
}
})
}
var viewModel = new RoleViewModel();
ko.applyBindings(viewModel);
【问题讨论】:
-
您是否获得了有效数据?它怎么不工作?
-
@gfish3000 是的,我得到了有效的数据作为响应……但是循环中卡住了一些东西……即使我在“for循环”中也没有收到任何警报……
-
您必须发布更多信息。例如:我看不到您将任何内容放入角色的位置,这意味着您的可观察数组长度始终为零,并且您永远不会看到警报,因为您从未进入 for 循环。你能发布一个 jsfiddle 吗?
-
@Paul 现在我已经编辑了有问题的代码部分,请检查并给我打电话...
-
HTML 是什么样的?你是如何驾驶你的模型的?你是如何调用更新的?