簡體   English   中英

另一個對象達到特定狀態后如何運行功能

[英]How to run function after another object reaches certain state

我有游戲 我有3個文件app.js,game.js,modal.js。 模態在模態的“下一步”按鈕上設置事件偵聽器,並跟蹤“ currentStep”。 也就是說,模態具有多個步驟。 現在,我希望僅在用戶完成模態之后才在app.js文件中啟動游戲。 在我的模態中,我有:

constructor(){
    this.currentStep = 0;

}
complete() {
    return (this.currentStep >= 4 ? true : false);
}

activate() {
   ....



    nextButton.addEventListener( 'click' , (e) => {

       if (this.currentStep === 0) {
          firstInstructions.classList.add('hideMe');
          firstGif.classList.remove("hideMe");  
          ....    
       }else if (this.currentStep === 4) {
          modal.classList.add("hideMe");
       }
    this.currentStep++;
});

}

現在,基本要點是我想以某種方式讓我的app.js知道用戶何時完成Modal,以便我可以運行game.play();。 所以像:

 const game = new Game();
 const modal = new Modal();
 modal.activate();

 // game.play() WHEN modal.complete

有人能建議Modal在發生這種情況時讓App知道它已經完成的正確方法。 我知道我可以使用while循環並繼續檢查modal.complete()以及何時運行game.play(),但這似乎是錯誤的。 謝謝。

我可以想到兩種方式,一種是您可以像這樣直接添加激活游戲本身。

const game = new Game();
const modal = new Modal();
modal.activate(game);

然后在激活中,您可以執行以下操作:

activate (game) {
   ....



   nextButton.addEventListener( 'click' , (e) => {

     if (this.currentStep === 0) {
       firstInstructions.classList.add('hideMe');
       firstGif.classList.remove("hideMe");  
       ....    
     } else if (this.currentStep === 4) {
       modal.classList.add("hideMe");

       // Put it here
       game.play();
     }
  this.currentStep++;
};

那就是如果最后一個模態步驟將開始游戲。 但是,如果您真的想將其放入完整方法中。 您也可以這樣做

const game = new Game();
// put the game inside the Modal constructor
const modal = new Modal(game);
modal.activate();

然后將游戲放入構造函數方法中

constructor (game) {
  this.currentStep = 0;
  // put it here
  this._game = game;
}

然后,您可以使用完整的方法從游戲中調用游戲

complete () {
  this._game.play();
  return (this.currentStep >= 4 ? true : false);
}

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM