docs: update the listener for custom node with dom demo.

This commit is contained in:
Yanyan-Wang 2020-06-01 14:33:11 +08:00 committed by Yanyan Wang
parent b00bce3519
commit ec87d7067f

View File

@ -9,15 +9,15 @@ import G6 from '@antv/g6';
/**
* 注册一个带有 DOM 的节点
*/
G6.registerNode('dom-node', {
draw: (cfg, group) => {
const stroke = cfg.style ? cfg.style.stroke || '#5B8FF9' : '#5B8FF9';
const shape = group.addShape('dom', {
attrs: {
width: cfg.size[0],
height: cfg.size[1],
html: `
<div onclick="alert('Hi')" style="background-color: #fff; border: 2px solid #5B8FF9; border-radius: 5px; width: ${cfg.size[0] - 5}px; height: ${cfg.size[1] - 5}px; display: flex;">
<div id=${cfg.id} class='dom-node' style="background-color: #fff; border: 2px solid ${stroke}; border-radius: 5px; width: ${cfg.size[0] - 5}px; height: ${cfg.size[1] - 5}px; display: flex;">
<div style="height: 100%; width: 33%; background-color: #CDDDFD">
<img alt="" style="line-height: 100%; margin-left: 7px;" src="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ" width="20" height="20" />
</div>
@ -29,7 +29,7 @@ G6.registerNode('dom-node', {
});
return shape;
}
}, 'single-node');
});
/** 数据 */
const data = {
@ -71,3 +71,41 @@ const graph = new G6.Graph({
graph.data(data);
graph.render();
// click listener for dom nodes to response the click by changing stroke color
const listener = (dom) => {
const nodeId = dom.id;
const node = graph.findById(nodeId);
let stroke = '';
if (!node.hasState('selected')) {
stroke = '#f00';
graph.setItemState(node, 'selected', true);
} else {
stroke = '#5B8FF9';
graph.setItemState(node, 'selected', false);
}
graph.updateItem(nodeId, {
style: {
stroke
}
});
}
const bindClickListener = () => {
const domNodes = document.getElementsByClassName('dom-node')
for (let i = 0; i < domNodes.length; i++) {
const dom = domNodes[i];
dom.addEventListener('click', (e) => {
listener(dom);
});
}
}
bindClickListener();
// after update the item, all the DOMs will be re-rendered
// so the listeners should be rebinded to the new DOMs
graph.on('afterupdateitem', e => {
bindClickListener();
});