问题:我是 KnockoutJS 的新手。以下示例代码正在为我工作。但您可以看到 fetch 功能是硬编码的,仅适用于 id = 100 的用户。如何为html表格列表中的每一行创建获取链接,并将该记录的 id 传递给获取功能,该功能仅显示记录控制台中的那一行。任何的想法?
HTML:
<div id="users-view-data">
<button type="button" data-bind="click: fetch">Get</button>
<button type="button" data-bind="click: remove">Delete</button>
<button type="button" data-bind="click: listAll">Get All</button>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Code</th>
<th>Created</th>
<th>Action</th>
</tr>
<tbody data-bind="foreach: collection">
<tr>
<td><span data-bind="text: id"></span></td>
<td><span data-bind="text: name"></span></td>
<td><span data-bind="text: code"></span></td>
<td><span data-bind="text: created"></span></td>
<td>Get Link will come here to call fetch funtion</td>
</tr>
</tbody>
</table>
</div>
JS:
<script type="text/javascript">
(function() {
'use strict';
var UserViewModel = function() {
this.service = ko.rest.service('http://domain/users');
this.model = ko.observable( { id:0, name:'', code:'' } );
this.collection = ko.observableArray([]);
};
UserViewModel.prototype.listAll = function() {
var self = this;
self.service.query(function(data) {
self.collection(data);
});
};
UserViewModel.prototype.fetch = function() {
var self = this;
self.service.load(100, function(data) {
self.model(data);
console.log(data);
});
};
UserViewModel.prototype.remove = function() {
var self = this;
var code = ko.rest.get(self.model(), 'id');
self.service.delete(code, function(data) {
console.log(data);
});
};
ko.applyBindings( new UserViewModel(), document.getElementById("users-view-data") );
})();
</script>
我正在使用以下库:
答案 0 :(得分:2)
如果我在正确理解了您的内容后,您需要将100
替换为对当前ID的引用,如下所示:
UserViewModel.prototype.fetch = function() {
var self = this;
self.service.load(self.model().id, function(data) {
self.model(data);
console.log(data);
});
};
答案 1 :(得分:1)
为每一行添加一个点击处理程序:
<tr data-bind="click:function(){$root.fetch(id)}">
<td><span data-bind="text: id"></span></td>
<td><span data-bind="text: name"></span></td>
</tr>
修改你的获取功能以获取一个id:
UserViewModel.prototype.fetch = function(id) {
var self = this;
//do whatever with id
};