cocos creator之事件:监听、发射、派送

版权声明:转载请注明出处 https://blog.csdn.net/nk1212582/article/details/81632049

版权声明:转载请注明出处 https://blog.csdn.net/nk1212582/article/details/81632049

事件监听

事件处理是在节点(cc.Node)中完成的。

对于组件,可以通过访问节点this.node来注册和监听事件。

监听事件可以通过this.node.on()方法和this.node.once()方法来注册。

node.on(type, callback, target)

cc.Class({
  extends: cc.Component,

  properties: {
  },

  onLoad: function () {
    this.node.on('mousedown', function ( event ) {
      console.log('Hello!');
    });
  },  
});

上述代码就是通过this.node.on()方法监听鼠标按下事件mousedown,事件发现时会触发函数

function(event){console.log("Hello!");}

值得一提的是,on()方法还可以传第三个参数target,用于绑定响应函数的调用者,其用法如下

// 使用函数绑定
this.node.on('mousedown', function ( event ) {
  this.enabled = false;
}.bind(this));

// 使用第三个参数
this.node.on('mousedown', function (event) {
  this.enabled = false;
}, this);

两种用法的效果一样

node.once(type, callback, target)

once()方法与on()方法基本一样,只有一点不同:正如其名,once()注册的事件只能监听一次,在监听函数响应后就会自动关闭监听事件

关闭监听

使用node.off(type, callback, target)方法来关闭对应的监听事件

off()方法的参数必须和对应的on()方法的参数一一对应,才能成功关闭

推荐写法如下

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);
  },
});

发射事件

可以通过两种方式发射事件:emit 和 dispatchEvent。

两者的区别是,dispatchEvent可以做事件传递(冒泡传送)

node.emit(type, detail)

通知所有监听 type 事件的监听器,detail是附加参数

cc.Class({
  extends: cc.Component,

  onLoad: function () {
    this.node.on('say-hello', function (event) {
      console.log(event.detail.msg);
    });
  },

  start: function () {
    //发射事件say-hello,所有注册过事件say-hello的函数都会被触发,say-hello是用户自定义事件
    this.node.emit('say-hello', {
      msg: 'Hello, this is Cocos Creator',
    });
  },
});

派送事件

通过dispatchEvent()方法发射的事件,会进入事件派送阶段。

CC的事件派送系统采用冒泡派送的方式。

冒泡派送:事件从发起节点开始,不断迭代地向父节点传递,直到遇到根节点或者在响应函数中进行了中断处理

event.stopPropagation()的节点。

如上图所示,但我们从节点c发送事件“footbar”,如果节点a, b均监听了事件“footbar”,则事件会经由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();
})

猜你喜欢

转载自blog.csdn.net/nk1212582/article/details/81632049