Cocos Creator脚本开发(三)

来源:互联网 发布:k11防水涂料与js怎么样 编辑:程序博客网 时间:2024/05/29 13:42

事件处理是在节点(cc.Node)中完成的。对于组件,可以通过访问节点 this.node 来注册和监听事件。监听事件可以 通过 this.node.on() 函数来注册

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

事件监听函数 on 可以传第三个参数 target,用于绑定响应函数的调用者。除了使用 on 监听,我们还可以使用 once 方法。once 监听在监听函数响应后就会关闭监听事件。

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

当我们不再关心某个事件时,我们可以使用 off 方法关闭对应的监听事件。需要注意的是,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。两者的区别在于,后者可以做事件传递。

cc.Class({  extends: cc.Component,  onLoad: function () {    this.node.on('say-hello', function (event) {      console.log(event.detail.msg);    });  },  start: function () {    this.node.emit('say-hello', {      msg: 'Hello, this is Cocos Creator',    });  },});
0 0
原创粉丝点击