appzone_oto
appzone_oto

Reputation: 333

Knockout js: how can i pass an argument to a knockout click function?

I have html button which has a n onclick function which takes the parameter of username this is my code and the knockout-model class :

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

this is the model class, with the removefriend function :

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;

}

This code works, but with one slight error, when the page loads, the function gets called without me even clicking the button. why is this and how can i stop it

Upvotes: 0

Views: 222

Answers (1)

user3297291
user3297291

Reputation: 23372

When the binding is applied (ko.applyBindings), the binding's value is evaluated. Since your binding value is an actual call to the method, it runs removeFriend.

If you want to bind an argument to the function without calling it, you can use bind:

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

You can also create a method that returns a function in your viewmodel:

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

with click: friendRemover(user.userName).

Upvotes: 2

Related Questions