Prevent triggering of parent group (group events bubble up)

妖精的绣舞 提交于 2019-12-11 08:59:27

问题


If you add an eventhandler to a group (not an element like rectangle) and this group also contains a group with an eventhandler and you trigger an event on the child group (click), it will also trigger the parents eventhandler. Fiddle How can you prevent that the parent is triggered? If you add the handlers to the rectangles, the event doesn't bubble up.

    var svgElement=document.getElementById("mainSvgId");
    var s = Snap(svgElement);
    s.attr({height: 300, width: 300});

    var parentGroup=s.g().attr({id: "parent"});
    var rect1 = s.rect(0, 0, 200, 200).attr({fill: "#bada55"});
    parentGroup.add(rect1);
    parentGroup.click(function(){
        console.log("id parent: " + this.node.id);
    })

    var childGroup=s.g().attr({id: "child"});
    var rect2 = s.rect(100, 100, 30, 30).attr({fill: "#ff0055"});
    childGroup.add(rect2);
    parentGroup.add(childGroup);
    childGroup.click(function(){
        console.log("id child: " + this.node.id);
    })

回答1:


You only have to change last 4 lines to prevent the event from propagating on it's parents:

    childGroup.click(function(e){
        e.stopPropagation()
        console.log("id child: " + this.node.id);
    })

updated FIDDLE



来源:https://stackoverflow.com/questions/24308701/prevent-triggering-of-parent-group-group-events-bubble-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!