【问题标题】:Phaser - access DOM elements using getChildByName outside of create functionPhaser - 使用GetChildByName访问Create功能的访问DOM元素
【发布时间】:2021-11-14 01:22:13
【问题描述】:

我在 create 函数中将 html 表单添加到我的画布中。我希望能够在用户按下Enter 键时提交表单。为此,我添加了关键侦听器并在更新函数中寻找JustDownPhaser.Input.Keyboard 的回调。但是有一个问题,当我从 update() 回调中调用我的 validateFrom 方法时,它无法使用 getChildByName 函数获取值。当我从 create() 回调中调用 validate Form 函数时,同样可以正常工作。

我的代码如下:

export default class Identity extends Phaser.Scene {

   constructor() {
    super({ key: "ABC" });
    this.enterKeyIdentity;
    
    console.log("constructor ....")
  }

    preload() {
      this.load.html("identity_form", "/assets/forms/Unlock1/identity.html");
    }

   create() {
      this.formInput = this.add.dom(0, 0).createFromCache("identity_form");
      this.formInput.originX = 0;
      this.formInput.originY = 0;

      this.enterKeyIdentity = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
      
      // the input values are fetched fine when accessed from here       
      this.formInput.getChildByName("submit").onclick = () => {
        this.validateFormIdentity();
      };

   }

   update () {
    if(Phaser.Input.Keyboard.JustDown(this.enterKeyIdentity)) {
      console.log("pressed down");
      this.validateFormIdentity(); // input values are not fetched properly when called from here
    }
  }

  validateFormIdentity = () => {
    console.log("submit called")
    let city1 = this.formInput.getChildByName("city1").value;
    let city2 = this.formInput.getChildByName("city2").value;
    let city3 = this.formInput.getChildByName("city3").value;

    console.log(city1, city2, city3)
    // prints actual values when invoked from create function
    // prints empty "" spaces when invoked from update function
 
  }

}

【问题讨论】:

    标签: javascript reactjs phaser-framework


    【解决方案1】:

    对于未来的读者,我最终使用了 vanilla javascript 中的 addListener 函数,而不是使用 Phaser 提供的输入键侦听器,如下所示。之后它工作正常。我仍然找不到不工作的原因。

    this.formInput.addListener('keypress');
    this.formInput.on('keypress', (e) => {
      if(e.code === "Enter") {
        validateFormIdentity()
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-05
      • 2014-03-18
      • 2021-09-05
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多