官网大部分案例都是用js写的,不过ts写法也大同小异,这里就记录一下刚入门的监听吧,新手入门如有错误请大家多多指点
通过事件机制来写程序,能让你的代码更优美
cocosCreater实现监听主要有以下几个步骤
1.接收者注册事件
this.node.on('foobar', this._sayHello, this);
2.事件分发者分发事件
this.node.dispatchEvent( new cc.Event.EventCustom('foobar',true));
最后一个参数为允许使用冒泡派送往父对象派送消息
注意:使用this.node进行事件分发只能在同一节点上进行,cc.director.emit('')可以惊醒全局事件分发
3.最后关闭监听
this.node.off('foobar', this._sayHello, this);
4.回调函数,参数event除了提供target外还有很多API
_sayHello(event) {
console.log('Hello World');
cc.log(event.target.name);//输出事件接受者的name
}
最后附上工程链接:自定义事件监听