"click: $parent.foo" vs "click: function(){ $parent.foo(); }"

60 views
Skip to first unread message

Jonny Mohawk

unread,
Sep 13, 2016, 3:30:41 AM9/13/16
to KnockoutJS
I hope I can explain this clearly... I have a single page app that I threw together pretty quickly. It started getting unmanageable so I just added requireJS, broke the html up into templates, and converted the js to typescript modules. The only reason I say all that is because through this process I stopped using self = this (although if you use lamba functions in TS it pretty much does the same thing except it compiles to _this = this). I also moved several functions to the prototype of the object it belong to. Once I did that I saw what seemed to be odd behavior but, maybe it isn't, I don't know, I'm not the best at javascript.

I was hoping someone could explain it to me...What I found was this:

Assume that you have
collection: {
   items: []
}
collection.prototype.foo()

then inside  foreach: item you have

<button data-bind="click: $parent.foo">
<button data-bind="click: function(){ $parent.foo(); }">

If you click the 1st button the value of this will = item
If you click the 2nd button the value of this will = collection

I am glad they work differently so I didn't have to undo all the prototyping I just did but, I was hoping someone could explain why they work differently.

Thanks,
Jon

noirabys

unread,
Sep 13, 2016, 7:35:18 AM9/13/16
to KnockoutJS
hi,
if you use the short syntax:
click: $parent.foo 
knockout will use $data as parameter for the function

if you use an anonymous function:
you simple call foo on $parent which is the collection and pass no arguments.
you may add the parameter:
click: function(){ $parent.foo($data);}

best regards,
  noirabys


btw there is no need for requireJS since knockout can asynchronously load components and their models.

Jonny Mohawk

unread,
Sep 13, 2016, 2:19:42 PM9/13/16
to KnockoutJS
Ahh that makes complete sense! 
Thanks
Reply all
Reply to author
Forward
0 new messages