如何在mxGraph连接时获取mxConnectionConstraint定义的连接点名称
获取mxGraph连接对应的自定义连接点名称
解决方案
当连接通过自定义mxConnectionConstraint建立后,可通过两种方式获取连接点名称:
1. 监听连接创建事件
利用mxEvent.CONNECT事件,在连接完成后直接从边缘(edge)的几何信息中提取约束名称:
// 监听连接创建事件 graph.addListener(mxEvent.CONNECT, function(sender, evt) { const edge = evt.getProperty('edge'); const geometry = edge.getGeometry(); // 获取源节点的连接点名称 if (geometry.sourceConstraint) { console.log('源连接点:', geometry.sourceConstraint.name); } // 获取目标节点的连接点名称 if (geometry.targetConstraint) { console.log('目标连接点:', geometry.targetConstraint.name); } });
2. 重写mxGraph的connect方法
在重写方法中直接获取传入的约束参数,还可将约束信息持久化到边缘的几何对象中:
// 保存原connect方法 const originalConnect = graph.connect; // 重写connect方法 graph.connect = function(edge, source, target, sourceConstraint, targetConstraint, dx, dy) { // 调用原方法完成连接 originalConnect.apply(this, arguments); // 直接获取连接点名称 if (sourceConstraint) { console.log('源连接点名称:', sourceConstraint.name); } if (targetConstraint) { console.log('目标连接点名称:', targetConstraint.name); } // 可选:将约束信息存入edge的geometry,方便后续获取 const geo = edge.getGeometry(); geo.sourceConstraint = sourceConstraint; geo.targetConstraint = targetConstraint; this.model.setGeometry(edge, geo); };
注意事项
- 确保自定义的
mxConnectionConstraint正确传入了名称参数(如示例中的'top'、'bottom') - 若之前重写
connect方法未成功,检查是否正确调用了原方法,以及是否正确接收sourceConstraint和targetConstraint参数
内容的提问来源于stack exchange,提问作者EaBengaluru
相关产品推荐
相关产品推荐

