Button添加事件
Button 目前只支持 Click 事件,即當用戶點擊並釋放 Button 時才會觸發相應的回調函數。
通過腳本代碼添加回調
方法一
這種方法添加的事件回調和使用編輯器添加的事件回調是一樣的,通過代碼添加, 你需要首先構造一個 cc.Component.EventHandler 對象,然后設置好對應的 target, component, handler 和 customEventData 參數。
//here is your component file, file name = MyComponent.js
cc.Class({
extends: cc.Component,
properties: {},
onLoad: function () {
var clickEventHandler = new cc.Component.EventHandler();
clickEventHandler.target = this.node; //這個 node 節點是你的事件處理代碼組件所屬的節點
clickEventHandler.component = "MyComponent";//這個是代碼文件名
clickEventHandler.handler = "callback";
clickEventHandler.customEventData = "foobar";
var button = node.getComponent(cc.Button);
button.clickEvents.push(clickEventHandler);
},
callback: function (event, customEventData) {
//這里 event 是一個 Touch Event 對象,你可以通過 event.target 取到事件的發送節點
var node = event.target;
var button = node.getComponent(cc.Button);
//這里的 customEventData 參數就等於你之前設置的 "foobar"
}
});
方法二
通過 button.node.on('click', ...) 的方式來添加,這是一種非常簡便的方式,但是該方式有一定的局限性,在事件回調里面無法 獲得當前點擊按鈕的屏幕坐標點。
//假設我們在一個組件的 onLoad 方法里面添加事件處理回調,在 callback 函數中進行事件處理:
cc.Class({
extends: cc.Component,
properties: {
button: cc.Button
},
onLoad: function () {
this.button.node.on('click', this.callback, this);
},
callback: function (event) {
//這里的 event 是一個 EventCustom 對象,你可以通過 event.detail 獲取 Button 組件
var button = event.detail;
//do whatever you want with button
//另外,注意這種方式注冊的事件,也無法傳遞 customEventData
}
});
