2013-04-30 96 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

相關問題