How to unbind an onload event on an external SVG after it was initially completed?

123 Views Asked by At

I have a rather complex and special issue. I have a div container which is initially hidden (display: none) and which is shown when a user clicks a button (using the jQuery function show()). Within this div is a svg visualization.

HTML

<div id="parent">
    <object id='myObject' type="image/svg+xml"></object>
</div>

Javascript

The SVG vis I am loading with the following code:

fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})


myObject.onload = function() { // wait for the svg has loaded

    var myObject = this; // we're in the object's load event handler.
    var svg = d3.select(myObject.contentDocument) // get the contentDocument
        .select("svg"); // then get the svg inside
    //...some more styling things happen here
}

My issue is, that I don't know how (a.k.a. where) I should unbind the onload event because it gets triggered each time the user clicks on the button to change the display mode of the parent div. When I use the following code ...

fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})
    .then(function() {return myObject.onload = null})

... it never applies the style settings I perform within the onload function. Also when I add the myObject.onload = null setting to the end of my button's click event it won't fire the onload function.

What am I missing here?

1

There are 1 best solutions below

0
Paul LeBeau On

Have you tried something like this?

fetch('LINK TO THE SVG FILE')
  .then(function(r) {return r.blob()})
  .then(function(b) {
     myObject.onload = function() { // wait for the svg has loaded
       // ...do what you need to...
       myObject.unload = null;
     }
     myObject.data = URL.createObjectURL(b)
  });