Is there a way in javascript to get a class to dispatch a custom event. Then have the object created from that same class listen for the custom event dispatch from the parent class. Thanks!
Sort of yes. JavaScript does not have a native Observer implementation, so you’ll either have to build it yourself or use a framework such as YUI, Google Closure, or others.
Thanks for the response. I tried creating my own custom class. The dispatch event works in the class. When I try to add the even listener on the object that was created from the parent class in my html <script>, it doesn’t work. Below is the code snippet, hopefully it’s not to confusing. Thanks!
//This is my JS class
//Custom Event
var event = new CustomEvent("DISPATCH", {
detail: {
message: "TEST"
}
});
function Header(introsound, question){
this.div = document.createElement("div");
this.div.setAttribute("id", "header");
document.body.appendChild(this.div);
}
//Function with dispatch event inside of it
Header.prototype.doThisFunction = function(){
//Dispatch Event
dispatchEvent(event);
};
//Event Listner
addEventListener("DISPATCH", newMessageHandler, false);
//Event Handler
function newMessageHandler(e){
console.info("Event is: ", e);
console.info("Custom data is: ", e.detail);
}
<div>
<script type="text/javascript">
var qheader = new Header();
//EventListener
document.getElementById("header").addEventListener("DISPATCH", newMessageHandler, false);
//This calls the function with the dispatch even inside of it
qheader.doThisFunction();
//Event Handler
function newMessageHandler(){
window.alert("bla");
}
</script>
</div>
I believe “addEventListener” and “dispatchEvent” are methods of DOM elements, not standalone functions. See this example:
Thanks for the reference.