Reputation: 2166
I am building an event manager for a little game that I am creating and have stumbled on a little problem (I don't know if it is a design pattern problem or if there is a solution to it)!
Take below for example;
o.Events = (function() {
"use strict";
function mousedown() {
// Set mousedown boolean
// # How can I change o.Events.mousedown
// For each layer
this.layers.forEach(function(layer) {
// Layer is listening
if (layer.listening && layer.mouse.x && layer.mouse.y) {
console.log("mousedown");
}
});
};
function init(game) {
// Mousedown boolean
this.mousedown = false;
game.element.addEventListener("mousedown", mousedown.bind(game), false);
};
function Events(game) {
// Initialize events
init.call(this, game);
};
return Events;
})();
How can I change the Events.mousedown
flag even though I am binding game so that inside the function this
is actually game?
Thanks
Upvotes: 0
Views: 86
Reputation: 664375
You will need to use a closure if you can't bind it. And I wouldn't bind the mousedown
function to game
either, as it's not a method on it. Simplicity rules:
o.Events = function Events(game) {
"use strict";
this.mousedown = false;
var that = this;
game.element.addEventListener("mousedown", function mousedown(e) {
/* use
e - the mouse event
this - the DOM element ( === e.currentTarget)
that - the Events instance
game - the Game instance (or whatever was passed)
*/
that.mousedown = true;
// For each layer
game.layers.forEach(function(layer) {
// Layer is listening
if (layer.listening && layer.mouse.x && layer.mouse.y)
console.log("mousedown");
});
}, false);
};
Upvotes: 1