CocosCreator 메시지 배포 메커니즘 상세 정보

3572 단어 Cocos메시지 배포

개요


이 편은 게임 업무 구조와 관련된 내용을 소개하기 시작했다.게임 업무층에서 모든 격리가 필요한 시스템과 모듈 간의 통신은 메시지 분배를 통해 결합을 풀 수 있다.예를 들어 네트워크 복귀 알림, 데이터 업데이트가 인터페이스에 동기화되는 등이다.
메시지 분배는 관찰자 모델을 바탕으로 설계되었다.메시지를 처리해야 하는 지역 방향 메시지 센터에 감청 리셋을 등록하고 메시지를 보낼 때 메시지 센터의 전송 인터페이스를 호출하여 이 메시지의 감청 대기열을 훑어보고 대응하는 리셋 방법을 호출합니다.

구체적 방안


먼저 감청 콜백 유형 정의

/**
 *  
 */
export type NotifyListener = (src: any, data: any) => void;
키-value 방식으로 감청 대기열 저장

private static msg2listDict: Dictionary< string, Array<NotifyListenerInfo> > = new Dictionary< string, Array<NotifyListenerInfo> >();
인터페이스 정의

/**
 *  , 
 * @param msg
 * @param listener
 * @param target
 */
public static addListener(msg: string, listener: NotifyListener, target?: any): void {}
 
/**
 *  , 
 * @param msg
 * @param listener
 * @param target
 */
public static addOnceListener(msg: string, listener: NotifyListener, target?: any): void {}
 
/**
 *  
 * @param msg
 * @param listener
 */
public static removeMsgListener(msg: string, listener: NotifyListener): void {}
 
/**
 *  
 * @param msg
 */
public static removeMsgAllListeners(msg: string): void {}
 
/**
 *  
 * @param msg
 * @param target
 */
public static removeTargetMsgListen(msg: string, target: any): void {}
 
/**
 *  
 * @param target
 */
public static removeTargetAllMsgListen(target: any): void {}
 
/**
 *  
 * @param msg
 * @param src
 * @param data
 */
public static notify(msg: string, src: any, data: any): void {}
제거 추가 중 메시지가 발송될 수 있음을 주의해야 합니다.
메시지에 새로 추가된 감청자는 현재 대기열 메시지를 보낸 후에 보내야 합니다. 따라서 추가할 대기열을 추가해야 합니다

private static listener2add: Array<NotifyListenerInfo> = [];
감청자 추가 시 아래 판단

//  , 
if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) {
    NotifyCenter.listener2add.push(info);
    return;
}
마찬가지로 감청자를 제거할 때 메시지를 보내고 있을 수 있습니다. 대기열에 대한 수정으로 인해 for순환 이상이 발생하지 않도록 합니다. 제거할 대기열을 추가합니다. 메시지를 보낼 때 이 감청자가 대기열을 제거하면 보내지 않습니다.메시지 발송이 끝난 후에 대기열에서 이동합니다

private static listener2remove: Array<NotifyListenerInfo> = [];
감청자를 제거할 때 다음과 같은 판단을 하다

//  , 
if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) {
    NotifyCenter.listener2remove.push(list[i]);
} else {
    list.splice(i, 1);
}
메시지를 보낼 때 지정한 메시지 아래의 대기열을 반복합니다

//  , 
let list = NotifyCenter.msg2listDict.get(msg);
if (!list) {
    return;
}
 
//  , , 
NotifyCenter.notifyMsgs.push(msg);
 
//  
for (let i = 0, n = list.length; i < n; i++) {
    NotifyCenter._dispatch(list[i], src, data, false);
}
메시지를 보낼 때 대기열을 제거할지 여부를 판단합니다

//  , 
if (NotifyCenter.listener2remove.indexOf(info) >= 0) {
    return;
}
현재 대기열 발송 후 추가 대기열 확인

//  
for (let i = 0, n = msg2add.length; i < n; i++) {
    if (listener2add[i].msg == msg) {
        NotifyCenter._dispatch(listener2add[i], src, data, true);
    }
}
메시지 분배 센터를 도입하여 격리된 시스템, 모듈 간에 메시지 감청과 발송 통신을 통해 상호 인용 결합을 피한다.
다음은 CocosCreator 메시지 배포 메커니즘에 대한 상세한 내용입니다. CocosCreator 메시지 배포에 대한 더 많은 자료는 저희 다른 관련 글을 주목해 주십시오!

좋은 웹페이지 즐겨찾기