Cocos Creator踩坑篇:事件机制问题和this问题整合

经过一天的研究,终于搞明白以下两个让人匪夷所思的事实

  • Cocos的node.on和node.emit只能在同一脚本内触发。。。Excuse me?这要他有什么用?
  • Cocos的node.on和node.dispatchEvent也只能在同一父结点之下有效

解决方案一:还好拥有全局的cc.game.on以及cc.game.emit,不过这样貌似会浪费过多的性能,因为我猜测它触发事件也要走一遍所有的系统事件,所以可能会造成性能上的损失

解决方案二:既然Game依赖于EventManager实现,那我们自己写一个全局的EventManager岂不更好,官网文档说明https://docs.cocos.com/creator/api/zh/classes/EventTarget.html

奉上ts的export和import  https://beginor.github.io/2016/03/20/typescript-export-and-import.html

下面是个完整的范例

项目结构

新建GlobalVariable.ts


var NotificationCenter = new cc.EventTarget();


//默认导出NotificationCenter
export {NotificationCenter as default};

新建JumpButton.ts


const {ccclass, property} = cc._decorator;
import GlobalPars from '../Base/GlobalVariable';

@ccclass
export default class JumpButton extends cc.Component {
    PlayerJump(){
        GlobalPars.emit('playerJump');
    }
}

新建PlayerLogic.ts

const {ccclass, property} = cc._decorator;
import GlobalPars from '../Base/GlobalVariable';

@ccclass
export default class PlayerLogic extends cc.Component {

     onLoad () {
         GlobalPars.on('playerJump', function () {
             console.log('I am Jumping');
         });
     }

}

将JumpButton.ts绑定在按钮上,并注册点击事件(PlayerJump()),创建Player结点,将PlayerLogic挂载到上面,运行场景

说到这,也就涉及到了ts中的this问题(果然欠的技术债都要还啊),因为我发现在GlobalPars.on里面,不能直接写this.方法名,因为这样this默认为GlobaPars中的this,而不是当前节点的this,也就会导致报错

解决方法1        

  GlobalPars.on('playerJump', function () {
             this.Jump();
         },this);

解决方法2

let self = this;  
GlobalPars.on('playerJump', function () {
             self.Jump();
         });

解决方案3 

 GlobalPars.on('playerJump', ()=>this.Jump());

 

奉上两篇讲this和箭头函数(兰布达表达式)的文章

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值