0

我想将 TypeScript 与 jsTree 一起使用。如何setCurrentNode在绑定的 jsTree 函数中调用该函数?

class MyController {
    thescope: any;
    static $inject = ['$scope'];

    constructor($scope) {
        $scope.vm = this;
        this.thescope = $scope;

        (<any>$("#demo2")).jstree({
             .bind("select_node.jstree", function (e, data) {
              // how can I call setCurrentNode(data) here?
             }
        });

    }


    setCurrentNode(node: any): any {
        ... // do Stuff in this typescript function
    }
}
4

4 回答 4

1

解决方案:

(<any>$("#demo2")).jstree({
         .bind("select_node.jstree", this.setCurrentNode.bind(this) )
         }

public setCurrentNode(e:any,data: any): any {
   ...
}
于 2013-08-14T10:45:38.923 回答
1

我不完全确定,所以如果我错了,请纠正我,但是使用lamba表达式是否也能解决这个问题?

如下:

class MyController {
    thescope: any;
    static $inject = ['$scope'];

    constructor($scope) {
        $scope.vm = this;
        this.thescope = $scope;

        (<any>$("#demo2")).jstree({
             .bind("select_node.jstree", (e, data) => {
                 this.setCurrentNode(e, data);
             }
        });

    }

    setCurrentNode(e: any, node: any): any {
        ... // do Stuff in this typescript function
    }
}

lambda ( =>) 表达式将确保函数在与您定义它的范围相同的范围内执行。如果您查看已编译的 JavaScript 代码,您会看到他将保留对构造函数范围的引用,并且将调用setCurrentNode该范围。简化示例:

var _this = this;
$("#demo2").jstree({
     .bind("select_node.jstree", (e, data) => {
         _this.setCurrentNode(e, data);
     });

我相信这会解决你的问题?

附带说明一下,您应该查找 jsTree 定义文件或至少自己添加一个存根声明,这样您就不需要将 JQuery 强制转换为任何文件。只是我的2cts,对我来说看起来很丑。

于 2013-08-14T11:48:11.703 回答
1

根据 Anzeo 的建议,以防止需要将 $ 转换为以下任何内容,您只需开始:

interface JQuery{
        jstree:Function;
}
于 2013-08-14T19:20:28.873 回答
0

它发生的是内部 jsTree 回调正在覆盖 this 对实例对象的初始引用。

有两种安全的方法可以解决这个问题:

1-通过使用@Anzeo 所指的箭头函数,我不推荐也从不使用它,因为如果您需要另一个嵌套回调,那么您可以对最里面的事件对象进行 this 引用。

2-通过缓存对实例对象的 this 引用,例如:

class MyController {
    thescope: any;
    static $inject = ['$scope'];

    constructor($scope) {
        // Caching the reference for using it in the inner callbacks.
        var self = this;

        $scope.vm = this;
        this.thescope = $scope;

        (<any>$("#demo2")).jstree({
             .bind("select_node.jstree", function (e, data) {

              // Call to the instance method here!
              self.setCurrentNode(/*Node params here*/);
             }
        });

    }


    setCurrentNode(node: any): any {
        ... // do Stuff in this typescript function
    }
}

我建议您坚持使用2,因为它可以通过任何嵌套级别工作,并且您可以在每个嵌套回调中让 this 指向正确的事件对象。

请参阅Z 组合器和所有其他递归函数中的 Javascript 'this' 覆盖以获取更多参考,因为问题与此处相同。

于 2013-08-14T21:04:19.647 回答