removeEventListener for object data load

Viewed 586

I have added an event listener to catch the loading of an SVG after a user action.

HTML

<object id="mySVG" type="image/svg+xml" data="default.svg"></object>

JS

mySVG = document.getElementById('mySVG');
mySVG.addEventListener('load', function () {
  // work with SVG contentDocument
});
mySVG.setAttribute('data', 'new.svg');

After another user action, I am clearing out the SVG by loading a blank inline SVG

var svgUrl = URL.createObjectURL(new Blob(['<svg xmlns="http://www.w3.org/2000/svg" width="700" height="700"/>'], {'type':'image/svg+xml'}));
mySVG.setAttribute('data', svgUrl);

I looks like setting this blank SVG is also triggering the load event, which is undesirable. So I tried

mySVG.removeEventListener('load');

This gives me the error

TypeError: Not enough arguments to EventTarget.removeEventListener.

What is the correct syntax for removeEventListener in this context?

edit: method to set the blank SVG was incorrect, corrected after reading this.

2 Answers

You should name your function and then pass it as the second argument both to addEventListener and removeEventListener, like so:

mySVG = document.getElementById('mySVG');

function loadFunction() {
  // work with SVG contentDocument
}

mySVG.addEventListener('load', loadFunction);
mySVG.setAttribute('data', 'new.svg');

mySVG.setAttribute('data', 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22700%22%20height%3D%22700%22%2F%3E');


mySVG.removeEventListener('load', loadFunction);
<object id="mySVG" type="image/svg+xml" data="default.svg"></object>

removeEventListener requires at least two arguments, the event type ('load') and the listener to remove, so you have to reference the listener that was added previously for it to ve removed.

mySVG.removeEventListener('load'); should have a target as second parameter on which it listens events

Related