Question about "this" option in computeds

47 views
Skip to first unread message

frontend_dev

unread,
Sep 16, 2016, 7:47:37 PM9/16/16
to KnockoutJS
Normally I would write it like this:

this.fullName = ko.computed(function() {
   return this.firstName() + " " + this.lastName();
}, this);

But imho it is a bit confusing, and eslint complains as well.

So does:

this.fullName = ko.computed(function() {
   return this.firstName() + " " + this.lastName();
}.bind(this));

... have any side effects or other negative implications? Just stepped through the ko source, and it seems this is not the case, correct?


Would prefer this style, then it is also more clear what "this" really means here.

noirabys

unread,
Sep 19, 2016, 1:23:58 AM9/19/16
to KnockoutJS
hi,
i think the recommended way is to assign this to a local variable and reference that instead within the computed:

function WhatEver(){
  var self = this;
 self.fullName = ko.computed(function() {
   return self.firstName() + " " self.lastName();
 });

frontend_dev

unread,
Sep 19, 2016, 10:17:32 AM9/19/16
to KnockoutJS
Well, why is this recommended over using bind? Of course I know the "that / _this" pattern, but I avoid it in general (also with event handlers etc) and prefer "bind" instead.

But the actual question was if this has any side effects when using "bind" on ko computed / pureComputed functions.

Tested this with one VM in the meantime and it seems to work just fine. But want to go sure before changing even more code.

Therefore any insights would be helpful.

Michael Best

unread,
Sep 20, 2016, 4:24:42 PM9/20/16
to KnockoutJS
bind will work fine. 

frontend_dev

unread,
Sep 20, 2016, 8:27:17 PM9/20/16
to KnockoutJS
Thanks for the reply!
Reply all
Reply to author
Forward
0 new messages