首页 > 技术文章 > Cocos Creator cc.Event点击触摸事件详解

luorende 2018-02-02 04:44 原文

cc.Event事件
请不要直接创建 cc.Event 对象,因为它是一个抽象类,请创建 cc.Event.EventCustom 对象来进行派发。

cc.Class({
extends: cc.Component,
_sayHello: function () { console.log('Hello World'); },
onEnable: function () {
this.node.on('foobar', this._sayHello, this); //添加事件
},
onDisable: function () {
this.node.off('foobar', this._sayHello, this); //删除事件
},
});

当我们从节点 c 发送事件 “foobar”,倘若节点 a,b 均做了 “foobar” 事件的监听,则 事件会经由 c 依次传递给 b,a 节点。如:

// 节点 c 的组件脚本中
this.node.dispatchEvent( new cc.Event.EventCustom('foobar', true) );
如果我们希望在 b 节点截获事件后就不再将事件传递,我们可以通过调用 event.stopPropagation() 函数来完成。具体方法如下:

// 节点 b 的组件脚本中
this.node.on('foobar', function (event) {
event.stopPropagation();
});

推荐阅读