Knockout Click binding and the ‘this’ context
Join the DZone community and get the full member experience.
Join For FreeWhen 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)
public AddMember(member: MemberViewModel) { var self = this; // method body here }
You can do any of the following:
data-bind=”click: myFunction()” – this will pass in the current $data instance in by default data-bind=”click: function(data, event){ myFunction($data, data, event)}” – this will manually pass in the current $data instance data-bind=”click: myfunction.bind($data)”
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.
Published at DZone with permission of Derik Whittaker, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Mainframe Development for the "No Mainframe" Generation
-
Building a Flask Web Application With Docker: A Step-by-Step Guide
-
Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
-
What Is Istio Service Mesh?
Comments