Derik Whittaker



Knockout Click binding and the ‘this’ context

When using Knockout JS wiring to the click binding is cake and simply just works.  Or does it?

Per the documentation there are multiple ways to wire the click binding within your html.  Assume you have a method such as (the code below is TypeScript)

You can do any of the following:

All of the above will accomplish the same goal, passing in the current $data object into the underlying method.  However, what appears to be the same is actually quite different.  The difference comes in when you are going to use the ‘this’ context.  Lets take a deeper look.

‘this’ context for option 1:


‘this’ context for option 2:


‘this’ context for option 3:


Did you notice the difference?  2 of the options (1 & 3) set the ‘this’ context equal to the passed in $data object.  Option 2 has the context set to the $parent object (in our case the view model).

Now I am NOT saying which one is right and which one is wrong because they are all right.  However, I just want to make sure everyone is aware of the differences.  In many cases i use option 2 because I want direct access to the underlying view model and this provides this.

I am sure there are many different ways in JavaScript/Knockout to get the parent View Model but honestly I like low friction and option 2 provides this for me.

Till next time.

Posted 04-29-2013 8:05 AM by Derik Whittaker
Filed under: ,



rémi bourgarel wrote re: Knockout Click binding and the ‘this’ context
on 04-29-2013 10:40 AM


I has the same problem last week. I just did this : data-bind="click:AddMember.bind($root)"

social bookmarking service wrote re: Knockout Click binding and the ‘this’ context
on 06-06-2013 7:13 PM

GTxlSy Enjoyed every bit of your post.Really looking forward to read more. Cool.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)