公司项目开发时,采用了go.js绘制节点关系图,需添加右键功能,采坑经历分享。
go.js API文档不太好懂,开发功能时,建议从实例入手,然后再去看API文档查找相关属性用法 就很容易理解了。如图:
1.添加右键功能,如下图:
右键属性contextMenu,贴代码:
//定义一个简单节点,右键属性contextMenu在节点内添加
myDiagram.nodeTemplate =
$(go.Node, "Auto",
{ contextMenu: myContextMenu },
$(go.Shape, "RoundedRectangle",
// Shape.fill is bound to Node.data.color
new go.Binding("fill", "color")),
$(go.TextBlock,
{ margin: 3 }, // some room around the text
// TextBlock.text is bound to Node.data.key
new go.Binding("text", "key"))
);
// ContextMenu,添加右键菜单,绑定事件,自定义菜单样式
var myContextMenu = $("ContextMenu",
$("ContextMenuButton",
$(go.TextBlock, "剪切",{
alignment: go.Spot.Center,
margin: 5,
font: "12px sans-serif",
opacity: 0.75,
stroke: "#404040"
}),
{ click: function(e, obj) { handleCut(obj,'0');}
}),
$("ContextMenuButton",
$(go.TextBlock, "复制",{
alignment: go.Spot.Center,
margin: 5,
font: "12px sans-serif",
opacity: 0.75,
stroke: "#404040"
}),
{ click: function(e, obj) { handleCopy(obj,'1'); } }
),
$("ContextMenuButton",
$(go.TextBlock, "删除",{
alignment: go.Spot.Center,
margin: 5,
font: "12px sans-serif",
opacity: 0.75,
stroke: "#404040"
}),
{ click: function(e, obj) { handleDelete(obj,'2'); } }),
$("ContextMenuButton",
$(go.TextBlock, "变色",{
alignment: go.Spot.Center,
margin: 5,
font: "12px sans-serif",
opacity: 0.75,
stroke: "#404040"
}),
{ click: function(e, obj) { handleColor(obj,'3'); } }));
//右键事件
function handleCut(){console.log('剪切')};
function handleCopy(){console.log('复制')};
function handleDelete(){console.log('删除')};
function handleColor(){console.log('变色')};
注意!!此处的坑:版本问题,还有层级嵌套的节点组
1. go.js版本最好为GOJS 2.1 版本以上,目前测试过1.7 、1.8 版本,都不兼容添加右键功能,莫名其妙抛错;
2. 有层级嵌套的节点组,groupTemplate,nodeTemplate节点模板定义里都要添加右键属性contextMenu,如图:
以上就是右键添加的实现。