John S.
John S.

Reputation: 514

Why is viewmodel function code executing on load?

There is a function in my viewmodel that is being executed as soon as the page loads.

I have a button that will simply show an alert (for now):

<button type="button" class="btn btn-outline-primary waves-effect waves-light" data-bind="click: $root.showData('user')">POS User</button>

and here is my ENTIRE view model:


let User = function(id, firstName, lastName, email, phone, isActive ){
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
  this.phone = phone;
  this.isActive = isActive;
}


function UsersViewModel () {

    var self = this; // Scope Trick

    // User, Customer, Tech
    self.currentUserType = 
    ko.observable("posUser");

    // Arrays
    self.posUsers    = ko.observableArray();
    self.customers   = ko.observableArray();
    self.technicians = ko.observableArray();

    self.currentUsers = ko.observableArray();


    self.currentUsers.push(new User(12,"John","Smith","[email protected]","800-333-3333",true));


    self.showData = function(userType){
        alert(userType);
    }
};


ko.applyBindings(new UsersViewModel());

See how it shows alert on load? Function Firing

Any ideas why this is happening?

Upvotes: 0

Views: 49

Answers (1)

Sam
Sam

Reputation: 1707

Here's two ways of solving your issue:

wrap your function in another function:

<button data-bind="click: function () { $root.showData('user'); }">POS User</button>

if you're in a context, like with: user or in a foreach with $data you can just do like below and in your function the first parameter will be your current context:

<!-- ko with: user -->    
<button data-bind="click: $root.showData">POS User</button>
<!-- /ko -->

self.showData = function (user) { ... };

as a somewhat unrelated remark, have you thought about your abbreviation 'POS' and what it reads in full to a lot of people? :)

Upvotes: 1

Related Questions