jquery - 如何从 Angular 2 组件调用 jstree On 函数

标签 jquery angular jstree

我使用下面的代码从我的 Angular 2 组件之一初始化 jstree

declare var $: JQueryStatic;

createTree(): void {
    $("#tree").jstree({
        "core": {
            "stripes": true
        },
        "plugins": ["types", "dnd"],
            'types': {
                "queue": {
                    "icon": "fa fa-list-ol"
                },
                "email": {
                    "icon": "fa fa-envelope-o"
                },
                "folder": {
                    "icon": "fa fa-folder-open-o"
                }
            }
        });
}

我必须将 jstree 函数添加到 index.d.ts 文件中的 JQuery 接口(interface)才能被 TypeScript 识别

interface JQuery {
    jstree(options?: any): JsTree;
}

该函数按预期工作,并且我的 TreeView 已成功生成。我现在想要执行下一步,将 jstree On 函数绑定(bind)到我的 JsTree 对象。我添加了JsTree接口(interface)

interface JsTree {
    on(event: string, callback: Function): void;    
}

并更改 createTree 方法以包含 On 函数

createTree(): void {
    $("#tree").jstree({
        "core": {
            "stripes": true
        },
        "plugins": ["types", "dnd"],
            'types': {
                "queue": {
                    "icon": "fa fa-list-ol"
                },
                "email": {
                    "icon": "fa fa-envelope-o"
                },
                "folder": {
                    "icon": "fa fa-folder-open-o"
                }
            }
        }).on('changed.jstree', function (e, data) {
            console.log(data.selected[0]);
        });
}

然而,这给了我一个

TypeError: Object doesn't support property or method 'on'

异常。我声明了正确的接口(interface)还是缺少其他内容?

最佳答案

实现此功能的最简单方法是将 JsTree 初始化包装到单独的 javascript 文件中它自己的函数中,并在 Angular 2 组件中公开该函数,下面我列出了步骤

第 1 步 - 将 JsTree 初始化提取到单独的 javascript 文件中它自己的函数

function InitJsTree(){
    $("#tree").jstree({
        "core": {
            "stripes": true
        },
        "plugins": ["types", "dnd"],
            'types': {
                "queue": {
                "icon": "fa fa-list-ol"
            },
            "email": {
                "icon": "fa fa-envelope-o"
            },
            "folder": {
                "icon": "fa fa-folder-open-o"
            }
        }
    })
}

第 2 步 - 请记住将 javascript 文件包含到您的 HTML 页面或页面中包含的缩小包中

第 3 步 - 在 Angular 2 组件类顶部声明 javascript 函数,并将其类型设置为 any

declare var InitJsTree: any;

第 4 步 - 在 Angular 2 组件中使用新公开的 javascript 方法

createTree(): void {
    InitJsTree();
}

关于jquery - 如何从 Angular 2 组件调用 jstree On 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39128646/

相关文章:

jquery - 更改日期颜色

javascript - 使用 jQuery 加载 CSS 而不将样式应用到页面

javascript - JQuery $.ajax - 未调用 done()

javascript - 如何将具有只读成员的javascript对象复制到非只读成员?

angular - Angular2 http GET 请求的问题

javascript - 如何回滚无法在jstree中移动的节点

angular - AngularFireAuth : cannot find name 'auth' (error: T2304) 类型上不存在属性身份验证

css - ionic2 - 更改 .loadcontent 的字体属性

python - 修改前序树遍历为Python结构

php - 如何从 etrepat/baum laravel 包导出 jstree 所需的 json 格式