G6: 如果对自定义node中的具体一个shape绑定事件?

Created on 18 Sep 2018  ·  4Comments  ·  Source: antvis/G6

G6.registerNode('cf', {
    draw(item: any) {
        const group = item.getGraphicGroup();
        const model = item.getModel();
        const {x, y, width, height} = model;

        const keyRect = group.addShape('rect', {
            attrs: {
                x,
                y,
                width,
                height,
                fill: 'green'
            }
        });

        const minorRect = group.addShape('rect', {
            attrs: {
                x: x + 50,
                y: y + 50,
                width: width + 50,
                height: height + 50,
                fill: 'red'
            }
        });

       // 尝试绑定事件
        keyRect.on('click', function () {
           // 无法正常相应
            console.log('hei');
        });

        minorRect.on('click', function () {
            console.log('hi');
        });

        return keyRect;
    }
});

如上述代码,预期对自定义node中的一个shape绑定一个事件,使用on方法,但是经过实际测试发现无效。文档中提及,group会调用G的api完成绘制,可是G是支持事件绑定的,而且实际观察断点的输出结果,事件也是绑定上了,但是没有任何相应,请问是哪里出了问题?需要怎么做?多谢

Most helpful comment

以下是我的一个实现,供参考。

  1. 在添加Shape时,为每一个Shape增加一个不同的name属性。
G6.registerNode('node', {
    draw: function draw(item) {
        var group = item.getGraphicGroup();
        group.addShape('text', {
            name: 'shapeName',
            attrs: {
                x: 0,
                y: 0,
                fill: '#999',
                text: item.id,
                textBaseline: 'top',
                textAlign: 'center'
            }
        });
    }
})
  1. 在click事件中根据Shape的name执行不同的逻辑。
var graph = new G6.Graph({
    container: 'mountNode'
});
graph.on('node:click', function(ev) {
    const shapeName = ev.shape.get('name');
    if (shapeName) {
        // do something
    }
});

All 4 comments

为了性能考虑,G6 中的事件统一委托给 graph,不走传统事件的冒泡捕获的流程。

以下是我的一个实现,供参考。

  1. 在添加Shape时,为每一个Shape增加一个不同的name属性。
G6.registerNode('node', {
    draw: function draw(item) {
        var group = item.getGraphicGroup();
        group.addShape('text', {
            name: 'shapeName',
            attrs: {
                x: 0,
                y: 0,
                fill: '#999',
                text: item.id,
                textBaseline: 'top',
                textAlign: 'center'
            }
        });
    }
})
  1. 在click事件中根据Shape的name执行不同的逻辑。
var graph = new G6.Graph({
    container: 'mountNode'
});
graph.on('node:click', function(ev) {
    const shapeName = ev.shape.get('name');
    if (shapeName) {
        // do something
    }
});

赞,小伙要不要来封简历:[email protected]

3.0版本的要用ev.target.get('name')获取。ev.shape已经undefined了

Was this page helpful?
0 / 5 - 0 ratings