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