event management update

beta.r3js.org
-=yb4f310 2017-10-27 09:38:07 +02:00
parent 062c5daa03
commit 15914c44db
1 changed files with 65 additions and 8 deletions

View File

@ -106,6 +106,7 @@ GameLib.Event.REGISTER_DEPENDENCIES = 0x58;
GameLib.Event.GAME_LOADED = 0x59;
GameLib.Event.GAME_RESTART = 0x5a;
GameLib.Event.LOAD_PROGRESS = 0x5b;
GameLib.Event.ENTITY_LOADED = 0x5c;
/**
* Returns string name of event ID
@ -207,6 +208,7 @@ GameLib.Event.GetEventName = function(number) {
case 0x59 : return 'game_loaded';
case 0x5a : return 'game_restart';
case 0x5b : return 'load_progress';
case 0x5c : return 'entity_loaded';
break;
}
@ -436,14 +438,44 @@ GameLib.Event.Emit = function(
}
}
/**
* We need to execute all the callbacks, but not execute them twice, but also keep in mind they can remove
* themselves during execution
*/
var length = GameLib.Event.Subscriptions[eventName].length;
for (var i = 0; i < length; i++) {
var object = GameLib.Event.Subscriptions[eventName][i];
if (object.fn && object.executed === false) {
object.fn(data, clientCallback, clientErrorCallback);
object.executed = true;
}
if (length !== GameLib.Event.Subscriptions[eventName].length) {
/**
* this callback removed a subscription - reset i and reset the length
*/
i = 0;
length = GameLib.Event.Subscriptions[eventName].length;
}
}
GameLib.Event.Subscriptions[eventName].map(
function(callback) {
if (callback) {
callback(data, clientCallback, clientErrorCallback);
count++;
}
function(object){
object.executed = false;
}
)
//
// GameLib.Event.Subscriptions[eventName].map(
// function(callback) {
// if (callback) {
// callback(data, clientCallback, clientErrorCallback);
// count++;
// }
// }
// )
} else {
if (clientCallback) {
/**
@ -468,10 +500,20 @@ GameLib.Event.Subscribe = function(
) {
if (GameLib.Event.Subscriptions.hasOwnProperty(eventName)) {
GameLib.Event.Subscriptions[eventName].push(fn);
GameLib.Event.Subscriptions[eventName].push(
{
fn : fn,
executed : false
}
);
} else {
GameLib.Event.Subscriptions[eventName] = [];
GameLib.Event.Subscriptions[eventName].push(fn);
GameLib.Event.Subscriptions[eventName].push(
{
fn : fn,
executed : false
}
);
}
/**
@ -480,8 +522,23 @@ GameLib.Event.Subscribe = function(
return {
fn : fn,
remove : function() {
var index = GameLib.Event.Subscriptions[eventName].reduce(
function(result, object, index) {
if (object.fn === fn) {
result = index;
}
return result;
},
-1
);
if (index === -1) {
throw new Error('could not remove subscription');
}
GameLib.Event.Subscriptions[eventName].splice(
GameLib.Event.Subscriptions[eventName].indexOf(fn),
index,
1
);
}