关于在 ts 中绑定事件,触发获取的值不变

  • Creator 版本: 2.4.3

  • 使用语言:typescript

@ccclass
export default class Game extends cc.Component {
  @property(cc.Node)
  cellAreaNode: cc.Node = null;

  cellNodeArr: nodeArr[] = [];

  onLoad() {
    this.initScene();
    
    console.log('onLoad: ', this, this.cellNodeArr)
    this.cellAreaNode.on("touchstart", this.onTouchStart, this);
  }
  onTouchStart(e: cc.Touch) {
    console.log('onTouchStart: ', this, this.cellNodeArr)
  }
}

具体流程是 initScene 填充 Node 节点到 cellNodeArr,然后当 cellAreaNode 触发 touchstart 事件时打印 cellNodeArr

在 onLoad 中打印的 cellNodeArr 是有值的,但是到了 onTouchStart 里面就变成了最开始的默认值 ‘[ ]’,试过直接传 this 当参数,用 on 的第三个参数指定 this 指向,但都不行

代码是看着 B 站视频做的,教程视频使用的是 javascript,然后运行成功了。。。萌新猜测这边是不是遭闭包了,一脸迷惑

望路过的大佬指点一下,非常感谢

this.initScene() 里面做了啥?只有部分代码也没法分析呀

把这一段放到onEnable中执行,并在onDisable中取消监听试一试

看你这张截图, onLoad和onTouchStart都没打印cellNodeArr啊