Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div click event automatically getting fired on page load

I want to create html page which has series of ( e.g.div has list of employee details ). When user click on div I want to navigate to another page. Please have a look at this.

Problem is click event of div is getting fired when I am loading page for the first time. How can I avoid unnecessary click events those are getting fired during page load event?

Below is my html code

<div data-bind="click: clickMe('ok1')">
    <h1>Emplyee details</h1>
    <p>This is test</p>    
</div>

<div data-bind="click: clickMe('ok2')">
    <h1>Emplyee details</h1>
    <p>This is test</p>    
</div>

var ViewModel = function(){
    var self = this;
    self.clickMe = function(url){   
        //This function is automatically getting called 
        //when page loads.
        alert(url);
    }
}
ko.applyBindings(new ViewModel());

Regards, Hemant

like image 476
user2243747 Avatar asked Jan 01 '14 14:01

user2243747


1 Answers

You need to pass a function to the click handler rather than the result of the click function.

Doing clickMe() fires the method and returns the result to the handler.

One way to do what you want is to wrap the function call in an anonymous function as so:

function(){ clickMe('params'); }  

So you get:

<div data-bind="click: function(){ clickMe('ok1'); }"> 

Alternatively you can use the bind function on your clickMe method to pass the params you want:

clickMe.bind($data, "param1") 

So you get:

<div data-bind="click: clickMe.bind($data, 'param1')"> 
like image 148
Jamie Dixon Avatar answered Sep 22 '22 06:09

Jamie Dixon