emit和.on的使用
由于做项目需要新手引导环节,ts也是和js一样同时进行的,想要实现完成一步再进行下一步就想到这个办法,因此进行记录。这里是使用CocosCreator进行开发。
emit是发送自定义事件,以字符串命名,例如: this.guideNode.parent.emit("FinshedAllGuide");
.on为接收事件,可以接收普通事件(具体可以搜索一下都有什么常见事件,点击移动滚轮),也可以接收自定义事件,例如:this.guideNode.parent.on("FinshedAllGuide", () => {console.log("接收成功")}, this);
this.guideNode.parent.on(cc.Node.EventType.TOUCH_END, (touch) => {console.log("成功")}, this);
发送事件和监听事件要挂到同一个节点,否则接收不到。
下面是给this.guideNode.parent添加了所有新手引导子页面数量的监听,只有当接收到自定义的this.clickEvent + String(index)事件时才触发,在完成了上一个才发送下一个。
@property(cc.Node)
guideNode: cc.Node = null;
@property(cc.Node)
maskNodes: cc.Node[] = [];
@property(cc.Node)
NextBtn: cc.Node = null;
@property(cc.Node)
jumpBtn: cc.Node = null;
clickEvent = "FinshedGuideClick"
onLoad() {
for (let index = 0; index < this.maskNodes.length; index++) {
this.guideNode.parent.on(this.clickEvent + String(index), this.addlisten, this)
}
}
//添加监听
addlisten() {
this.guideNode.active = true;
this.NextBtn.off(cc.Node.EventType.TOUCH_END);
// console.log("进去了addlisten")
for (let i = 0; i < this.maskNodes.length; i++) {
if (i == this.HowManyTime) {
this.maskNodes[i].active = true;
// console.log("显示maskNode" + i)
} else {
this.maskNodes[i].active = false;
// console.log("不显示maskNode" + i)
}
}
this.NextBtn.on(cc.Node.EventType.TOUCH_END, () => {
// console.log("我现在点击的是第", this.HowManyTime, "次引导!")
this.HowManyTime++;
if (this.HowManyTime < this.maskNodes.length) {
this.guideNode.active = false;
this.guideNode.parent.emit(this.clickEvent + String(this.HowManyTime));
console.log("emit发送的是", this.clickEvent + String(this.HowManyTime))
} else {
this.guideNode.parent.emit("FinshedAllGuide");
this.guideNode.off(cc.Node.EventType.TOUCH_START);
console.log("guide off关闭")
}
})
this.jumpBtn.on(cc.Node.EventType.TOUCH_START, () => {
this.guideNode.parent.emit("FinshedAllGuide");
this.guideNode.off(cc.Node.EventType.TOUCH_START);
console.log("guide off关闭")
})
//关闭事件下发使点击穿透不了
this.guideNode['_touchListener'].setSwallowTouches(false);
}
下面的代码是在主脚本上发送第一次的引导,调出引导页面。
@property(cc.Node)
guideNode: cc.Node = null;
//开始进行新手引导(写在主脚本里)
this.guideNode.active = true;
this.guideNode.parent.emit("FinshedGuideClick0");
//完成新手引导的回调(和开始写一块就行,只要接收到FinshedAllGuide事件就触发回调)
this.guideNode.parent.on("FinshedAllGuide", () => {
// this.tanchuFunc("完成新手引导")
}, this);