监听和发射事件

    值得一提的是,事件监听函数 on 可以传第三个参数 target,用于绑定响应函数的调用者。以下两种调用方式,
    效果上是相同的:

    1. // 使用函数绑定
    2. this.node.on('mousedown', function ( event ) {
    3. this.enabled = false;
    4. }.bind(this));
    5. this.node.on('mousedown', function (event) {
    6. this.enabled = false;
    7. }, this);

    除了使用 on 监听,我们还可以使用 once 方法。once 监听在监听函数响应后就会关闭监听事件。

    当我们不再关心某个事件时,我们可以使用 off 方法关闭对应的监听事件。需要注意的是,off 方法的
    参数必须和 on 方法的参数一一对应,才能完成关闭。

    我们可以通过两种方式发射事件:emitdispatchEvent。两者的区别在于,后者可以做事件传递。
    我们先通过一个简单的例子来了解 emit 事件:

    1. cc.Class({
    2. extends: cc.Component,
    3. onLoad: function () {
    4. this.node.on('say-hello', function (event) {
    5. console.log(event.detail.msg);
    6. });
    7. },
    8. start: function () {
    9. this.node.emit('say-hello', {
    10. msg: 'Hello, this is Cocos Creator',
    11. });
    12. },
    13. });

    上文提到了 dispatchEvent 方法,通过该方法发射的事件,会进入事件派送阶段。在 Cocos Creator 的事件派送系统中,我们采用冒泡派送的方式。冒泡派送会将事件从事件发起节点,不断地向上传递给他的父级节点,直到到达根节点或者在某个节点的响应函数中做了中断处理 event.stopPropagation()

    如果我们希望在 b 节点截获事件后就不再将事件传递,我们可以通过调用 event.stopPropagation() 函数来完成。具体方法如下:

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

    请注意,在发送用户自定义事件的时候,请不要直接创建 cc.Event 对象,因为它是一个抽象类,请创建 cc.Event.EventCustom 对象来进行派发。

    在事件监听回调中,开发者会接收到一个 cc.Event 类型的事件对象 event, 就是 cc.Event 的标准 API,其它重要的 API 包含:

    以上是通用的事件监听和发射规则,在 Cocos Creator 中,我们默认支持了一些系统内置事件,可以参考我们后续的文档来查看如何使用:

    • 鼠标、触摸:可参考