【问题标题】:How to define a custom connector in JointJS如何在 JointJS 中定义自定义连接器
【发布时间】:2021-10-19 08:29:29
【问题描述】:

我正在尝试在 Vue 的 JointJS 中定义一个自定义连接器。虽然我不认为这真的是 JointJS 问题或 Vue 问题,而是我对 Javascript 模块在这种情况下的工作方式缺乏了解......

我有这个代码,它似乎与文档匹配 (https://resources.jointjs.com/docs/jointjs/v3.3/joint.html#connectors.custom):

import Vue from 'vue';
let joint = Vue.joint;

joint.connectors = joint.connectors || {};

joint.connectors.CloudConflictConnector = function(sourcePoint, targetPoint, vertices, args)  
{
...
}

注意 Vue.joint 是作为插件创建的,这样:

const Joint = {
    install: function (Vue) {
        let joint = { g, dia, layout, linkTools, V };

        Object.defineProperty(Vue.prototype, '$joint', { value: joint });
        Vue.joint = Vue.prototype.$joint;
    }
};
Vue.use(Joint);

但是当我后来尝试使用这个连接器时,JointJS 中的findPath() 会抛出连接器不存在的错误。问题似乎是在findPath 中,它正在从 npm 包中导入连接器模块。该模块显然没有我添加到Vue.joint.connectors 属性的任何内容。

如果我尝试更直接地将函数添加到模块中,则会收到“对象不可扩展”错误。例如在插件中做这样的事情:

import * as connectors from 'jointjs/src/connectors/index.mjs';

const Joint = {
    install: function (Vue) {
        let joint = { g, dia, layout, linkTools, V, connectors };
        joint.connectors.customConnector = ...;

        Object.defineProperty(Vue.prototype, '$joint', { value: joint });
        Vue.joint = Vue.prototype.$joint;
    }
};
Vue.use(Joint);

所以我想问题是如何正确地将属性添加到模块导出中,以使其他直接导入模块的代码仍然可以看到它?我认为在 Vue 之外,这一切都可以正常工作,因为 joint 将是一个全局变量(?)

【问题讨论】:

    标签: javascript vue.js ecmascript-6 node-modules jointjs


    【解决方案1】:

    部分问题是插件创建了一个新的joint 对象,该对象缺少原始导入的connectors 属性。

    但是,我认为插件应该保留原始导入并在其上设置自定义连接器:

    export default {
      install(app) {
        const joint = require('jointjs')
        addCustomConnector(joint)
    
        app.prototype.$joint = joint
        app.joint = joint
      }
    }
    
    function addCustomConnector({ connectors }) {
      connectors.CloudConflictConnector = (sourcePoint, targetPoint, vertices, args) => {
        //...
      }
    }
    

    GitHub demo

    【讨论】:

    • 是的 - 从导入 JointJS 的各个部分切换到导入整个包(在我的例子中 - import * as joint from 'jointjs')解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多