2014-10-31 113 views
1

因此,我正在嘗試使用javascript模塊模式和html5畫布,通過製作簡單的基於html5的遊戲,並遇到了我的第一個障礙。我在畫布上偵聽mousemove事件。如何從事件函數模塊模式調用函數

init: function() { 
    var gameCanvas = document.getElementById("gameCanvas"); 
    gameCanvas.addEventListener("mousemove", this.redrawAvatar); 
} 

我在做的是讓我的頭像跟隨鼠標指針在畫布上的移動。

然後,問題是,我有我的模塊中的一些功能,我希望從redrawAvatar函數中調用,像這樣:

redrawAvatar: function (mouseEvent) { 
    var gameCanvas = document.getElementById("gameCanvas"), 
    avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY}, 
    enemyCoord = {x: 100, y: 100}; 

    this.clear(gameCanvas); 
    this.drawAvatar(avatarCoord); 
    this.drawEnemy(enemyCoord); 

    if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) { 
     alert("Avatar died, collided with enemy"); 
    } 
} 

雖然裏面redrawAvatar的這個對象是不是我的模塊了,但是是而不是事件(在這種情況下,畫布)

這裏的來源是我的模塊的精髓:

var MyGame = (function() { 

    var Game = { 

     draw: function (image, coord) {}, 

     drawAvatar: function (coord) {}, 

     clear: function (canvas) { canvas.width = canvas.width + 1 - 1;}, 

     drawEnemy: function (xPos, yPos) {}, 

     isCollision: function (a, b) {}, 

     redrawAvatar: function (mouseEvent) { 
      var gameCanvas = document.getElementById("gameCanvas"), 
       avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY}, 
       enemyCoord = {x: 100, y: 100}; 

      this.clear(gameCanvas); 
      this.drawAvatar(avatarCoord); 
      this.drawEnemy(enemyCoord); 
      if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) { 
       alert("Avatar died, collided with enemy"); 
      } 
     }, 

     init: function() { 
      var gameCanvas = document.getElementById("gameCanvas"); 
      gameCanvas.addEventListener("mousemove", this.redrawAvatar); 
     } 
    }; 

    (function() { 
     var that = Game; 
     that.init(); 
    }()); 

}()); 

我怎麼給函數在我想要打給我的模塊中?

回答

2

您可以使用bind在函數中使用當前上下文(在您的情況下是遊戲模塊),而不是事件的上下文。

gameCanvas.addEventListener("mousemove", this.redrawAvatar.bind(this)); 

這裏是一個基本的演示,重現綁定效果。它使用一個點擊事件。

var MyGame = (function() { 
 
     var Game = { 
 
      scoped: 5, 
 
      redrawAvatar: function (mouseEvent) { 
 
      alert(this.scoped); 
 
      }, 
 

 
      init: function() { 
 
       var gameCanvas = document.getElementById("d"); 
 
       gameCanvas.addEventListener("click", this.redrawAvatar.bind(this)); 
 
      } 
 
     }; 
 
     (function() { 
 
      var that = Game; 
 
      that.init(); 
 
     }()); 
 
    }());
<div id="d">Basic element for click handler (click for demo)</div>

運行的代碼片段或jsFiddle Demo

+0

完美!並且對mdn也有很好的參考。 – Rythmic 2014-10-31 22:37:48