Skip to content

Commit

Permalink
上传消息中心的js文件和readme文件
Browse files Browse the repository at this point in the history
  • Loading branch information
liuliji committed Nov 4, 2017
1 parent afaa443 commit 0fb15e6
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 0 deletions.
110 changes: 110 additions & 0 deletions MessageCenter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@

/************************************************************************
* Copyright (c) 2017 App
* Author : liji.liu
* Mail : liuliji1184899343@163.com
* Date : 2017-11-04
* Use : 消息中心
************************************************************************/

var bindFuncList = [];// 保存监听函数
/**
* bindFuncList结构如下
* [
* 'event1':[func1,func2],
* 'event2',[func3,func4]
* ]
*/
/**
* 当暂时没有监听,或者场景没有初始化的时候,会将提前收到的消息和数据,
* 保存到emitList中,结构如下:
* [
* 'event1':[args1,args2],
* 'event2':[args3,args4];
* ]
*/
var emitList = [];
/**
* 设置监听
* @param {监听的事件的名字} key
* @param {监听的回调方法} cbFunc
*/
// 设置事件监听
function on(key,cbFunc){
debugger;
if (bindFuncList[key]){
bindFuncList[key].push(cbFunc);
}else {
var ary = new Array();
ary.push(cbFunc);
bindFuncList[key] = ary;
}
}
/**
* 触发事件监听函数
* @param {监听的事件的名字} key
* @param {调用时传的参数} args
*/
// emit事件,发送消息
function emit(key,args){
var ary = bindFuncList[key];
if(ary){// 如果已经注册了事件,就直接发送消息
for (var i in ary) {
if (ary.hasOwnProperty(i)) {
try {
ary[i].call(this,args);
} catch (error) {
debugger;
}
}
}
}else {// 没有注册,先将要发送的消息保存,然后等待事件注册后,再一起emit
if (emitList[key]){
emitList[key].push(args);
}else {
var ary = new Array();
ary.push(args);
emitList[key] = ary;
}
}
}
// emitAll,将所有消息都emit
function emitAll(){
debugger;
for (var key in emitList) {
if (emitList.hasOwnProperty(key)) {
var emitAry = emitList[key];
for (var j in emitAry) {
if (emitAry.hasOwnProperty(j)) {
var args = emitAry[j];// 去除参数
var ary = bindFuncList[key];// 去除监听的方法
// 开始执行事件
for (var iterator in ary) {
if (ary.hasOwnProperty(iterator)) {
try {
ary[iterator].call(this,args);
} catch (error) {
debugger;
}
}
}

}
}
}
}
emitList = [];
}

// 清空全部的事件监听
function popAll(){
bindFuncList = [];
}

module.exports = {
'on': on,// 设置事件监听
'emit': emit,// emit事件,发送消息
'emitAll': emitAll,// emitAll,将所有消息都emit
'popAll': popAll,// 清空全部的事件监听
}

6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# MessageCenter
js , cocos creator
该文件适合在js项目中使用,用于在多个脚本之间进行通讯并发送消息。博主是用cocos Creator进行游戏开发的,其他的并不是很了解,所以,如果使用者是cocos creator使用者,可以使用该文件进行消息发送。
使用说明:
1. 在使用过程中,需要将该脚本引用到相应的js文件中去,然后,通过on方法来设置事件监听,通过emit来发送消息。popAll方法用来清空监听列表,emitAll用来派发之前没有发送出来的消息。
2. 在项目的脚本或者组件初始化的过程中。先调用on方法,设置所有的事件监听。然后emitAll,保证在监听设置的过程中,收到的网络消息不被丢弃。在emitAll方法中,会对消息进行判断,如果当前事件监听列表中没有事件监听,就先将收到的消息保存,然后等初始化完成并设置好事件监听后,统一调用emitAll方法,将所有的消息一起发出来。保证不丢包。
3. 在当前场景的根节点的destroy方法中,调用popAll方法,保证在当前场景销毁的时候,所有的监听被移除掉了。

0 comments on commit 0fb15e6

Please sign in to comment.