问题
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