如何通过不同的ID绑定具有相同敲除功能的多个链接

How to bind multiple links with same knockout function passing different IDs

问题:我是 KnockoutJS 的新手。以下示例代码对我有用。但是你可以看到 fetch 函数是硬编码的,并且只对 id=100 的用户有效。如何在 html table 列表中的每一行创建一个 Get link 并传递 id该记录的 fetch 函数仅显示控制台中该特定行的记录。任何想法?

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>

我正在使用以下库:

如果我正确理解您的意思,您需要将 100 替换为对当前 ID 的引用,如下所示:

UserViewModel.prototype.fetch = function() {
    var self = this;
    self.service.load(self.model().id, function(data) {
        self.model(data);
        console.log(data);
    });
};

为每行添加一个点击处理程序:

<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
};

(simplified) fiddle