I'm trying to create an event for an object to have it listen to it. Consider the following example:
var moon;
moon = document.createEvent("Event");
moon.initEvent("Event",true,true);
var Dog = function (name) {
this.name = name;
document.addEventListener("Event",this.bark,false);
};
dog.prototype.bark = function() {
console.log(this.name + ': Awooooooof Woof!');
};
var spot = new Dog("Spot");
var dot = new Dog("Dot");
//invoke
document.dispatchEvent(moon);
I'm expecting to receive an output like:
Spot: Awooooooof Woof!
Dot: Awooooooof Woof!
But what I get is:
undefined: Awooooooof Woof!
What is wrong with my example? How can I register a listener that every instance of Dog has?
What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
JavaScript is not a class-based object-oriented language. But it still has ways of using object oriented programming (OOP). In this tutorial, I'll explain OOP and show you how to use it. The most popular model of OOP is class-based.
Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.
In this line
document.addEventListener("Event",this.bark,false);
you don't bind the scope of this.bark
to this
. In JavaScript, the value of this
does not depend on where the function is defined but from where it is called. This means when you pass this.bark
to addEventListener
you detach it from the current object.
In frameworks like prototype.js and JQuery there are shortcuts for binding this
, with vanilla JavaScript you can do it like this:
function bind(scope, fn) {
return function() {
return fn.apply(scope, arguments);
}
}
And then:
document.addEventListener("Event",bind(this, this.bark),false);
The problem you have is that this
inside the function does not refer to the object you want to manipulate.
How about adding the function bark
inside the function definition?
var Dog = function (name) {
this.name = name;
this.bark = function() {
console.log(name + ': Awooooooof Woof!');
};
document.addEventListener("Event", this.bark, false);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With