简体   繁体   中英

Javascript using bind within an object, how can I access object this?

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

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM