I have this structure:
___________________
| g1 __________ |
| | g2 | |
| | | |
| | ____ | |
| | | r1 | | |
| | |____| |
| |__________| |
|___________________|
Only the object on which fire
is called receives the event.
r1.fire('myevent')
r1.on('myevent',doSomething) //works
g2.on('myevent',doSomething) //not called
g1.on('myevent',doSomething) //not called
How can I trigger a fire
on a child element and have all parents receive the event?
Stack Snippet:
var canvas = SVG().addTo("body");
var g1 = canvas.group();
var g2 = g1.group(); //inside group1
var r1 = g2.rect(100, 100).fill("blue"); //inside group2
g1.on("customEvent", function (e) {
console.log("Custom event captured by group1");
});
g2.on("customEvent", function (e) {
console.log("event fired");
//this.parent().fire("customEvent");// this shouldn't be needed
});
// Trigger the custom event on rectangle2, manually propagate it up to both group1 and group2
r1.on("click", function () {
this.parent().fire("customEvent");
//this.parent().fire("customEvent");// this shouldn't be needed
});
r1.on("customEvent", function () {
console.log("event fired");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/3.2.0/svg.js"></script>
svg.js uses CustomEvents under the hood and you can pass options as third parameter to the
fire
method:This is public api but I realized its extremely hidden in the docs under: https://svgjs.dev/docs/3.1/events/#custom-events