淘汰赛js:我如何将一个参数传递给淘汰赛点击功能?

时间:2018-05-18 11:08:05

标签: knockout.js

我有一个html按钮,它有一个onclick函数,它接受用户名的参数,这是我的代码和淘汰模型类:

<span data-bind="if: friendRequestStatus() === 'ACCEPTED', click: removeFriend(user.userName())" class="call">remove<i class="fa fa-user"></i></span>

这是模型类,带有removefriend函数:

function usersProfileModel(data) {

var usersProfile = ko.mapping.fromJS(data);



usersProfile.user.fullName = ko.pureComputed(function() {

    return usersProfile.user.firstName() + " " + usersProfile.user.lastName();

});

usersProfile.user.playerStats.percentageWin = ko.pureComputed(function() {

    if(usersProfile.user.playerStats.matchPlayed()=== 0){

        return 0;

    }else {

        return (usersProfile.user.playerStats.wins() / usersProfile.user.playerStats.matchPlayed()) * 100;

    }

});


usersProfile.user.playerStats.percentageProfit =  ko.pureComputed(function() {

    if(usersProfile.user.playerStats.wallet() > 0.00){

        return (usersProfile.user.playerStats.profit() / usersProfile.user.playerStats.wallet()) * 100;

    }else {

        return 0;

    }

});

usersProfile.mutualFriendsPercentage =  ko.pureComputed(function() {

    if(usersProfile.mutualFriendsCount() > 0){

        return (usersProfile.mutualFriendsCount() / usersProfile.friendsCount()) * 100;

    }else {

        return 0;

    }

});

usersProfile.addFriend = function() {

    showNotification('top-right','info','Awaiting response', 250, 2000);

};

usersProfile.removeFriend = function(username) {


    alert(username);

    swal({

        toast:true,
        position: 'top-right',
        width: 250,
        title: 'Removing...',
        text: 'please hold on.',
        onOpen: () => {
            swal.showLoading()
        }
    }).then((result) => {

    });

    $.get("http://localhost:8080/friendrequest/send/" + username, function(data, status){

        self.usersOnScreen(data.content);
    });

};


return usersProfile;

}

此代码有效,但有一个小错误,当页面加载时,即使单击按钮也不会调用该函数。为什么这是我怎么能阻止它

1 个答案:

答案 0 :(得分:2)

当应用绑定(ko.applyBindings)时,将评估绑定的值。由于您的绑定值是对方法的实际调用,因此它运行removeFriend

如果你想绑定函数的参数而不调用它,你可以使用bind

click: removeFriend.bind($data, user.userName())

您还可以创建一个在viewmodel中返回函数的方法:

usersProfile.friendRemover = function(name) {
  return () => usersProfile.removeFriend(name());
}

click: friendRemover(user.userName)

相关问题