Cocos Creator scrollview添加事件的兩種方法


scrollview添加事件

方法一
這種方法添加的事件回調和使用編輯器添加的事件回調是一樣的,通過代碼添加, 你需要首先構造一個 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 scrollViewEventHandler = new cc.Component.EventHandler();
    scrollViewEventHandler.target = this.node; //這個 node 節點是你的事件處理代碼組件所屬的節點
    scrollViewEventHandler.component = "MyComponent";//這個是代碼文件名
    scrollViewEventHandler.handler = "callback";
    scrollViewEventHandler.customEventData = "foobar";

    var scrollview = node.getComponent(cc.ScrollView);
    scrollview.scrollEvents.push(scrollViewEventHandler);
},

//注意參數的順序和類型是固定的
callback: function (scrollview, eventType, customEventData) {
    //這里 scrollview 是一個 Scrollview 組件對象實例
    //這里的 eventType === cc.ScrollView.EventType enum 里面的值
    //這里的 customEventData 參數就等於你之前設置的 "foobar"
}

});

方法二
通過 scrollview.node.on('scroll-to-top', ...) 的方式來添加
//假設我們在一個組件的 onLoad 方法里面添加事件處理回調,在 callback 函數中進行事件處理:
cc.Class({
extends: cc.Component,
properties: {
scrollview: cc.ScrollView
},

onLoad: function () {
   this.scrollview.node.on('scroll-to-top', this.callback, this);
},

callback: function (event) {
   //這里的 event 是一個 EventCustom 對象,你可以通過 event.detail 獲取 ScrollView 組件
   var scrollview = event.detail;
   //do whatever you want with scrollview
   //另外,注意這種方式注冊的事件,也無法傳遞 customEventData
}

});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM