0

我正在为我正在创建的一个小游戏构建一个事件管理器,并且偶然发现了一个小问题(我不知道这是否是设计模式问题或者是否有解决方案)!

以下面为例;

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;

})();

Events.mousedown即使我正在绑定游戏,如何更改标志以使函数内部this实际上是游戏?

谢谢

4

1 回答 1

1

如果无法绑定,则需要使用闭包。而且我不会将mousedown函数绑定到game任何一个,因为它不是它的方法。简单规则:

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);
};
于 2013-05-01T01:50:30.983 回答