Typescript Knockout best way to retain 'this'?

人盡茶涼 提交于 2020-01-16 02:56:42

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17877103/typescript-knockout-best-way-to-retain-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!