如何将参数发送到点击绑定淘汰赛

时间:2016-08-16 19:52:31

标签: javascript knockout.js

我想向用户点击按钮时调用的函数发送一个值。

这是视图模型,

define(["knockout", "text!./index.html", "../../components/users/users"], function (ko, indexTemplate, userModel) {
function indexViewModel(params) {
    var self = this;
    var id = 1;
    self.users = ko.observableArray([]);
    $.ajax({
        url: 'server/getUsers.php',
        type: 'post',
        data: {"data":id},
        success: function (result) {
            var row = JSON.parse(result)
            for(var i=0;i<row.length;i++){
                self.users.push(new userModel.userModel(row[i]["name"],row[i]["time"],row[i]["id"]));
            }
        }
    });
    self.removeUser = function (user) {
       alert(user);
    };
    return self;
    }
return { viewModel: indexViewModel, template: indexTemplate };
});

这是html页面,

<!-- ko foreach: users -->
<div class="col-md-3 col-sm-6">
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="" style="height:180px;"></div>
        </div>
        <div class="panel-footer">
            <button class="btn btn-danger" data-bind="click: removeUser.bind($data,$data.id)">Remove</button>
        </div>
    </div>
</div>
<!-- /ko -->

我想在用户点击按钮时获取$ data.id。我试过removeUser.bind($ data,$ data.id),但是有一个错误。 removeUser未定义。

1 个答案:

答案 0 :(得分:1)

您没有定义removeUser,因为它位于父模型中,因此请尝试$parent.removeUser。 如果你想要的只是从数组中删除所选项目。然后尝试如下

<!-- ko foreach: users -->
<div class="col-md-3 col-sm-6">
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="" style="height:180px;"></div>
        </div>
        <div class="panel-footer">
            <button class="btn btn-danger" data-bind="click: $parent.removeUser">Remove</button>
        </div>
    </div>
</div>
<!-- /ko -->

并在模型中

define(["knockout", "text!./index.html", "../../components/users/users"], function (ko, indexTemplate, userModel) {
function indexViewModel(params) {
    var self = this;
    var id = 1;
    self.users = ko.observableArray([]);
    $.ajax({
        url: 'server/getUsers.php',
        type: 'post',
        data: {"data":id},
        success: function (result) {
            var row = JSON.parse(result)
            for(var i=0;i<row.length;i++){
                self.users.push(new userModel.userModel(row[i]["name"],row[i]["time"],row[i]["id"]));
            }
        }
    });
    self.removeUser = function () {
  self.users.remove(this);
    };
    return self;
    }
return { viewModel: indexViewModel, template: indexTemplate };
});