如何在PIXI.Sprite的pointerup事件中获取GameManager引用(不使用全局变量)
嘿,这个问题我太熟了!PIXI的事件回调默认会把触发事件的Sprite作为this上下文,想拿到GameManager的引用又不想用全局变量,有好几种靠谱的办法,给你挨个说:
箭头函数(最省心的方案)
箭头函数不会创建自己的this,它会直接继承外层作用域的this。如果你的GameManager是个类,在类方法里绑定回调时用箭头函数就行:// GameManager类中的方法 setupInteractiveSprite() { const spr = new PIXI.Sprite(yourTexture); spr.pointerup = () => { // 这里的this就是GameManager的实例! this.updateGameState(); console.log(this); // 输出GameManager对象 }; // 别忘了开启交互属性 spr.interactive = true; spr.buttonMode = true; }这种写法最简洁,不用额外处理上下文,直接就能拿到GameManager的引用。
用
bind()手动绑定上下文
如果你偏好普通函数,或者需要给回调传额外参数,bind()可以帮你把this固定成GameManager实例:setupInteractiveSprite() { const spr = new PIXI.Sprite(yourTexture); // 绑定this为当前GameManager实例,还能提前传参 spr.pointerup = this.handleSpriteClick.bind(this, "额外参数1", "额外参数2"); spr.interactive = true; spr.buttonMode = true; } handleSpriteClick(param1, param2, event) { // this是GameManager,event是PIXI的事件对象,event.currentTarget是触发的Sprite console.log(this); // GameManager实例 console.log(event.currentTarget); // 被点击的Sprite console.log(param1, param2); // 提前传入的参数 }注意
bind()的参数顺序:先写要绑定的this,再写需要传递的参数,最后回调函数会收到事件对象。闭包捕获GameManager引用
如果你的代码结构不是类,或者需要更灵活的上下文控制,闭包也是个经典解决方案:function GameManager() { const self = this; // 把GameManager的引用存到变量里 this.setupSprite = function() { const spr = new PIXI.Sprite(yourTexture); spr.pointerup = function(event) { // 用self访问GameManager,这里的this还是Sprite self.processClick(event); }; spr.interactive = true; spr.buttonMode = true; }; this.processClick = function(event) { console.log("GameManager处理点击事件", event.currentTarget); }; }这里通过闭包让回调函数能访问到
self变量,从而拿到GameManager的引用,完全不需要全局变量。类字段箭头函数(ES6+语法)
如果你的项目支持ES6类字段,还可以把回调方法直接定义成箭头函数,这样它的this会永久绑定到GameManager实例:class GameManager { // 类字段箭头函数,this自动绑定到GameManager实例 handleSpriteClick = (event) => { console.log(this); // GameManager实例 console.log(event.currentTarget); // 被点击的Sprite }; setupInteractiveSprite() { const spr = new PIXI.Sprite(yourTexture); spr.pointerup = this.handleSpriteClick; spr.interactive = true; spr.buttonMode = true; } }这种写法代码更整洁,不用在绑定回调时额外处理上下文,现代浏览器和主流打包工具都支持这个语法。
这些方案都完美避开了全局变量,你可以根据自己的代码结构和需求选最合适的~
内容的提问来源于stack exchange,提问作者Chiffie
相关产品推荐
相关产品推荐

