cocos creator 2.4
请问如何给内置事件发送数据呢?
以下这段代码能正常打印出testdata的值
let testdata = 1;
node.on("xxx",function(i){
cc.log(i);
},this);
node.emit("xxx",testdata);
而这段却会报错
[ERROR]: (see stack) Uncaught TypeError: event.stopPropagation is not a function [0]_onTouchEnded@src/cocos2d-jsb.js:29070
let testdata = 1;
node.on("touchend",function(i){
cc.log(i);
},this);
node.emit("touchend",testdata);
那么如何将testdata发送给 函数呢?
参考GPT和自己的思路:
在 cocos creator 2.4 中,可以通过 emit 函数将数据传递给内置事件的监听函数。但是在你的第二段代码中出现了错误,这是因为 "touchend" 事件是一个浏览器事件,需要使用 event.stopPropagation() 方法来阻止冒泡,而在此情况下,你没有事件对象,所以会报错。
如果你要给内置事件发送数据,建议你使用自定义事件的方式,例如:
let testdata = 1;
node.on("myEventName", function(i){
cc.log(i);
}, this);
node.emit("myEventName", testdata);
这样就可以将 testdata 传递给监听函数了。当然,为了更好的数据传递和处理,可以将数据封装在事件对象中,例如:
let event = new cc.Event.EventCustom("myEventName", true);
event.setUserData(testdata);
node.dispatchEvent(event);
然后在监听函数中获取数据:
node.on("myEventName", function(event){
let testdata = event.getUserData();
cc.log(testdata);
}, this);
这样可以更好地处理传递的数据。