Reputation: 73
i have problem with window.addEventListener.
THIS works:
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.resize);
},
resize:function(){alert("dupa");},
}
engine.eventListeners();
BUT THIS: doesn't:
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event.resize);
},
event:function(){
function resize(){alert("d");}
},
}
engine.eventListeners();
I dont know why becouse for me it should works.
I must use event();
60 times per second and inside event(); will be more functions
0 errors in console.
Upvotes: 0
Views: 70
Reputation: 2077
If I understand correctly what you want, the solution is convert your events
property in your engine
object into an object, like this:
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event.resize);
},
event:{ // You can have all your event methods here
resize: function(){
alert("d");
},
click: function(){
alert("Clicked")
},
change: function(){
alert("Changed")
}
}
}
engine.eventListeners();
Look how it works:
let i = document.querySelector("input"),
b = document.querySelector("button")
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event.resize);
b.addEventListener("click",this.event.click);
i.addEventListener("change",this.event.change);
},
event:{ // You can have all your event methods here
resize: function(){
console.log("Resized")
},
click: function(){
console.log("Clicked")
},
change: function(){
console.log("Changed")
}
}
}
engine.eventListeners();
<input placeholder="change my value"/>
<button>Click me</button>
<h1>Try resizing your window</h1>
Upvotes: 1
Reputation: 40842
For the code:
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event.resize);
},
event:function(){
function resize(){alert("d");}
}
}
the resize
function is defined within the scope of the anonymous function that you store in the event
property and as of that resize
can only be accessed from within that scope.
But you probably want to use an object for event
instead of a function:
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event.resize);
},
event: {
resize : function(){alert("d");}
}
}
engine.eventListeners();
That way you can access it using this.event.resize
.
Upvotes: 1
Reputation: 1
this.event is a function , you should return function from it and change it to this.event()
const engine = {
eventListeners:function(){
window.addEventListener("resize",this.event());
},
event:function(){
return function resize(){alert("d");}
},
}
Upvotes: -1