我想向用户单击按钮时调用的函数发送一个值。
这是视图模型,
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。
最佳答案
您正在获取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 };
});