cocos2d-js 实现观察者模式

前端之家收集整理的这篇文章主要介绍了cocos2d-js 实现观察者模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 手动管理观察者listenerName

2. 确保只有注册过的才能下发事件

3. 当前模式只支持唯一观察者listenerName,不支持共享

4. 在切换到登录界面时要清空所有listener

HelpTool._listenerList = {};

HelpTool.setListenerFlag = function(listenerNaMetable,flag) {
    for (var i = 0; i < listenerNaMetable.length; i++) {
        if (flag == false && HelpTool._listenerList[listenerNaMetable[i]]) {
            cc.eventManager.removeCustomListeners(listenerNaMetable[i]);
        }
        HelpTool._listenerList[listenerNaMetable[i]] = flag;
        cc.log("xiaohei " + (flag ? "enable" : "disable") + " listener id: " + listenerNaMetable[i]);
    }
};

HelpTool.disableAllListeners = function() {
    for (var k in HelpTool._listenerList) {
        HelpTool._listenerList[k] = false;
        cc.eventManager.removeCustomListeners(k);
        cc.log("xiaohei set and remove all listeners flag is false " + k);
    }
};

HelpTool.dispatchListener = function(listenerName,patchdata) {
    if (HelpTool._listenerList[listenerName]) {
        cc.log("xiaohei dispatch listener id: " + listenerName);
        var dataTable = patchdata || {};
        cc.eventManager.dispatchCustomEvent(listenerName,dataTable);
    } else {
        cc.log("xiaohei listener the " + listenerName + " flag is " + HelpTool._listenerList[listenerName]);
    }
};

注册
onExit: function() {
    HelpTool.setListenerFlag(["msg_superstar_currency_change","msg_superstar_state_change"],false);
},init: function() {
    // xiaohei add listener
    cc.eventManager.addCustomListener("msg_superstar_currency_change",function(args) {
        this.updateMoneyNum();
    }.bind(this));
    cc.eventManager.addCustomListener("msg_superstar_state_change",function(args) {
        this.onUpdateState();
    }.bind(this));
    HelpTool.setListenerFlag(["msg_superstar_currency_change",true);
},

下发:
HelpTool.dispatchListener("msg_superstar_currency_change");


注销:(主城的onExit中调用

onExit: function () {
  cc.AudioEngine.getInstance().stopMusic("res/audio/bgm/BGM_mainui_1.mp3");
  this._super();

  HelpTool.disableAllListeners();
  cc.log("#### HomeScene on exit");
}
原文链接:https://www.f2er.com/cocos2dx/339263.html

猜你在找的Cocos2d-x相关文章