Knockout click binding fires on page load! Either I'm completely wrong in usage or it's a bug

3,346 views
Skip to first unread message

thebitt...@gmail.com

unread,
Aug 5, 2012, 5:22:06 PM8/5/12
to knock...@googlegroups.com
Hello guys, I stumbled across this issue on Friday and I want to know what you think.
Here's a piece of markup I used:
   <th><span data-bind="click: myVmMethod('propertyName')">Some title<span</th>
myVmMethod is a function on my view model class that accepts one parameter. I was stunned when it turned out that the method code executed after page is loaded, not when I clicked on it. and since this is somewhat performance aggressive method, the browser hung happily.
I have found a workaround that uses an anonymous function instead of straight call to the method, but I'm curious - did I misunderstood something or is it really a Knockout bug? Didn't find it on Github though

Michael Best

unread,
Aug 6, 2012, 4:35:49 AM8/6/12
to knock...@googlegroups.com, thebitt...@gmail.com
The click binding expects you to give it a reference to the function, but you're just calling the function, which means that the click binding will just hold whatever is returned by your function. Besides using an anonymous function, you could also use 'bind': click: myVmMethod.bind( $data, 'propertyName')

See http://knockoutjs.com/documentation/click-binding.html, section "Note 2: Accessing the event object, or passing more parameters"

-- Michael

thebitt...@gmail.com

unread,
Aug 6, 2012, 9:28:42 AM8/6/12
to knock...@googlegroups.com, thebitt...@gmail.com
I see. I saw bind workaround, just couldn't get it to work. By the way, how exactly can I give the binding a reference to a function, not  a function itself without having to write anonymous function?

понедельник, 6 августа 2012 г., 12:35:49 UTC+4 пользователь Michael Best написал:

deanom...@gmail.com

unread,
Feb 9, 2018, 12:50:27 PM2/9/18
to KnockoutJS
Wrapping it in a function like this should take care of it:

<th><span data-bind="click: function() { myVmMethod('propertyName') }">Some title<span</th>

Squire

unread,
Sep 27, 2018, 7:40:32 AM9/27/18
to KnockoutJS

Nice one! This worked for me...

Ramell Lamar

unread,
Oct 24, 2018, 10:14:04 AM10/24/18
to KnockoutJS
This worked for me as well!! Thanks
Reply all
Reply to author
Forward
0 new messages