I just found out that FileReader dispatches events just as if it was a DOM element. Is it? I wonder if it’s possible to create an object similar to FileReader, which doesn’t have a representation in HTML/XML structure, but can dispatch events?
Share
FileReaderhas methods likeaddEventHandlerbecause it is defined to implement theEventTargetinterface.EventTargetis defined by the DOM Events spec but you don’t need to be a DOM object to implement it.window,XMLHttpRequestandFileReaderare other Browser Object Model objects that implementEventTarget.Unfortunately there’s no easy way to piggyback on the browser’s native implementation of event targets… you could try inheriting from a browser object by using one as a
prototypeproperty, but that’s very unreliable in general. However it is not too difficult to write code to implement all the methods yourself in plain JavaScript:Caution: the above code is off the top of my head and untested, but may work. However it has limitations like only supporting the
dispatchEventreturn value if theEventobject supports the DOM Level 3defaultPreventedproperty, and no support for DOM Level 3stopImmediatePropagation()(which is impossible to implement unless you rely on your own Event object that exposes a property for it). Also there’s no implementation of hierarchy or capture/bubbling.So IMO: you don’t gain much by trying to write code that participates in the DOM Events model. For plain-JS callback work I’d just go with your own ad hoc implementation of listener-lists.