Using lawnchair with Typescript

守給你的承諾、 提交于 2019-12-12 13:08:05

问题


Got a simple problem, which was touched upon in a similar question around the "this" scope with typescript.

I have a storage service which wraps lawnchair for my local storage concerns. Now I am migrating this code over to Typescript I have come to an issue I cannot solve.

public GetAll(callback: Function) {
           Lawnchair({ name: this.storeName }, function () {
                this.all(callback);
            });
        };

Now in the example above lawnchair makes this become the actual store you are actioning, but Typescript will make it become the instance of the class you are using. So is there a way around this issue?

== Edit ==

Updated the question example slightly as to not confuse with the underlying lawnchair method and the surrounding classes method.

Here is the error I get when trying to compile:

The property 'all' does not exist on value of type 'LawnchairStorageService'

Which is correct, that method does NOT exist on the containing class instance, it exists within the context of the lawnchair closure scopes this.


回答1:


As noted in the comments above, this compiles, and I think it ought to run:

public GetAll(callback: Function) {
    return function (callback){
        Lawnchair({ name: this.storeName }, function () {
            this.all(callback);
        });
    }(callback);
};

... but I suspect someone else may be able to weigh in with a more elegant solution.




回答2:


Have you tried the following :

public Exists(uniqueIdentifier: string, callback: Function) {
           var me = this;
           Lawnchair({ name: this.storeName }, function (me) {
                me.exists(uniqueIdentifier, callback);
            });
        };


来源:https://stackoverflow.com/questions/15679838/using-lawnchair-with-typescript

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