Pass Typescript function as a Javascript function

て烟熏妆下的殇ゞ 提交于 2019-12-12 02:28:14

问题


I use typescript with breeze. How can i pass a typescript function to executeQuery.then?

class MyClass{
 ...
    myFunc(data:any):void{
       ...
    }

    doQuery():void{
        var manager = new breeze.EntityManager('/breeze/dbentities');
        var query = breeze.EntityQuery.from("Corporations").where("Name", "startsWith", "Zen");
        manager.executeQuery(query)
               .then(this.myFunc);  // does not work!
    }
}

回答1:


Use this.myFunc instead of myFunc.

It might be a context problem. Try this.myFunc.bind(this) instead of this.myFunc.


For more information about context, refer "this" and "Function.prototype.bind" article from MDN.




回答2:


First, this is working perfectly in my own classes. What is "not working", what error message is thrown?

Second, to be sure that "this" is my typescript class context I always use a lambda like this:

doQuery(): void {
    ...
    manager.executeQuery(query).then((data: breeze.QueryResult) => {
        this.myFunc(data);
    });
}

In this case the TS compiler produces a "var _this = this" at the beginning of the doQuery function which is your class context and converts the "this.myFunc(data)" call to "_this.myFunc(data)".

And better use type declarations like "breeze.QueryResult" instead of any.



来源:https://stackoverflow.com/questions/17853644/pass-typescript-function-as-a-javascript-function

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