Files
oops-framework/assets/script/game/common/ecs/CCVMParentComp.ts

124 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* @Author: dgflash
* @Date: 2021-11-11 19:05:32
* @LastEditors: dgflash
* @LastEditTime: 2022-01-26 16:40:57
*/
import { Node, _decorator } from 'cc';
import { EventDispatcher } from "../../../core/common/event/EventDispatcher";
import { ecs } from "../../../core/libs/ECS";
import VMParent from "../../../core/libs/model-view/VMParent";
import { ViewUtil } from "../../../core/utils/ViewUtil";
const { ccclass, property } = _decorator;
/**
* Cocos Creator Component + ECS Comp + VM VMParent
* 使用方法:
* 1、对象拥有Cocos引擎组件功能、ECS 组件全局访问功能、显示对象与数据结构绑定功能
* 2、网络游戏优先有数据对象然后才创建视图组件在释放视图组件时不释放数据对象
* 3、对象自带监听、释放、发送全局消息功能
* 4、对象管理的所有节点摊平直接通过节点名获取cc.Node对象节点名不能有重名
*/
@ccclass('CCVMParentComp')
export abstract class CCVMParentComp extends VMParent implements ecs.IComp {
static tid: number = -1;
static compName: string;
canRecycle!: boolean;
ent!: ecs.Entity;
abstract reset(): void;
private nodes: Map<string, Node> = new Map();
/** 通过节点名获取预制上的节点,整个预制不能有重名节点 */
get(name: string): Node | undefined {
return this.nodes.get(name);
}
onLoad() {
ViewUtil.nodeTreeInfoLite(this.node, this.nodes);
super.onLoad();
}
//#region 全局事件管理
private _eventDispatcher: EventDispatcher | null = null;
public get eventDispatcher(): EventDispatcher {
if (!this._eventDispatcher) {
this._eventDispatcher = new EventDispatcher();
}
return this._eventDispatcher;
}
// 事件是否绑定node的active
private _isBindMessageActive: boolean = false;
/** 绑定node active属性即只有active为true才会响应事件 */
public bindMessageActive() {
this._isBindMessageActive = true;
}
/** 解绑node active属性无论node是否可见都会响应事件 */
public unbindMessageActive() {
this._isBindMessageActive = false;
}
/**
* 注册全局事件
* @param event(string) 事件名
* @param listener(function) 处理事件的侦听器函数
* @param thisObj(object) 侦听函数绑定的this对象
*/
public on(event: string, listener: Function, thisObj: any) {
this.eventDispatcher.on(event, (event, args) => {
if (!this.isValid) {
if (this._eventDispatcher) {
this._eventDispatcher.destroy();
this._eventDispatcher = null;
}
return;
}
if (this._isBindMessageActive) {
if (this.node.active) {
listener.call(thisObj, event, args);
}
}
else {
listener.call(thisObj, event, args);
}
}, thisObj);
}
/**
* 移除全局事件
* @param event(string) 事件名
*/
public off(event: string) {
if (this._eventDispatcher) {
this._eventDispatcher.off(event);
}
}
/**
* 触发全局事件
* @param event(string) 事件名
* @param arg(Array) 事件参数
*/
public dispatchEvent(event: string, arg: any = null) {
this.eventDispatcher.dispatchEvent(event, arg);
}
onDestroy() {
if (this._eventDispatcher) {
this._eventDispatcher.destroy();
this._eventDispatcher = null;
}
this.nodes.clear();
}
//#endregion
}