cocos creator之事件:監聽、發射、派送
事件監聽
事件處理是在節點(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();
})