1

This is an extra question to this TypeScript and Knockout binding to 'this' issue - lambda function needed? where two methods of retaining this inside a Knockout function is proposed:

class viewmodelclass {
    declaredinconstructor: (args) => void;
    constructor(public someobjects: Array) {
        this.declaredinconstructor=(args) =>{
        }
    }
    declaredoutside(args) {    
    }
    declaredoutsidecorrectly = (args) => {
        console.log(this);
    };
}

Producing this Javascript:

var viewmodelclass = (function () {
    var _this = this;
    this.declaredoutsidecorrectly = function (args) {
        console.log(_this);
    };
    function viewmodelclass(someobjects) {
        this.someobjects = someobjects;
        this.declaredinconstructor = function (args) {
        };
    }
    viewmodelclass.prototype.declaredoutside = function (args) {
    };
    return viewmodelclass;
})();

If you want to use this inside the functions, the following HTML code is needed:

<div data-bind="foreach: someobjects" >
   <a href="#" data-bind="click: $parent.declaredinconstructor">link 1</a>
   <a href="#" data-bind="click: $parent.declaredoutside.bind($parent)">link 2</a>
   <a href="#" data-bind="click: $parent.declaredoutsidecorrectly">link 3</a>
</div>

Both (should) work but which is the more correct/faster?

I prefer to declare it in the constructor because the HTML code is a bit nicer.

EDIT: Thanks to Basarat's video I remembered a video about Typescript - Typescript will help you retain this - by declaring _this in the produced Javascript - but only if necessary! (Had I not written console.log(this) _this would not be produced by Typescript.)

Conclusion - when declared correctly the outside implementation will not leak out to the HTML so the correct answer is, as Amitabh points out, to choose the pattern that is most efficient: Attaching the function to each instance or to the prototype.

Community
  • 1
  • 1
Rune Jeppesen
  • 1,121
  • 13
  • 22

2 Answers2

2

Definitely prefer pattern 1. The reason is that in pattern 2 the underlying implementation of the classes is leaking into the html which is bad in my book.

basarat
  • 261,912
  • 58
  • 460
  • 511
1

While I agree with BASarat that pattern 2 is leaking implementation to the html. But in pattern 1 if we have a list of viewModels then we are attaching the function to each instance of the object instead of attaching it to the prototype of the model. This might be an issue if we have a list with large no of Items.

So there can be cases when we might have to use pattern 2.

Amitabh
  • 59,111
  • 42
  • 110
  • 159