2013-04-30 50 views
0

我正在为一个小游戏构建一个事件管理器,我正在创建一个小游戏并且偶然发现了一个小问题(我不知道它是否是设计模式问题或者是否有解决方案)!Javascript在对象内使用绑定,我怎样才能访问这个对象?

以下面为例;

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实际上是游戏?

谢谢

+0

只需引用它的全部范围。 'o.Events.mousedown = ...' – Madbreaks 2013-04-30 21:28:23

+0

这将有助于看到一点客户端代码。也就是说,使用您创建的这个Events对象的代码。 – Jonah 2013-04-30 21:28:28

+0

在构造函数或mousedown(e)... e.target中使用“that = this”事件' – dandavis 2013-04-30 22:45:49

回答

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

感谢这使得更有意义 – GriffLab 2013-05-01 12:29:56

相关问题