event handler optimzation

This commit is contained in:
pypy
2020-01-11 17:15:39 +09:00
parent 149a2117b0
commit 45e75a9281
+30 -26
View File
@@ -204,44 +204,48 @@ if (window.CefSharp) {
var API = {}; var API = {};
API.$handler = {}; API.$eventHandlers = new Map();
API.$emit = function (event, ...args) { API.$emit = function (name, ...args) {
// console.log(name, ...args);
var handlers = this.$eventHandlers.get(name);
if (handlers === undefined) {
return;
}
try { try {
// console.log(event, ...args); for (var fx of handlers) {
var h = this.$handler[event]; fx.apply(this, args);
if (h) {
h.forEach((f) => f(...args));
} }
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
}; };
API.$on = function (event, callback) { API.$on = function (name, fx) {
var h = this.$handler[event]; var handlers = this.$eventHandlers.get(name);
if (h) { if (handlers === undefined) {
h.push(callback); handlers = [];
} else { this.$eventHandlers.set(name, handlers);
this.$handler[event] = [callback];
} }
handlers.push(fx);
}; };
API.$off = function (event, callback) { API.$off = function (name, fx) {
var h = this.$handler[event]; var handlers = this.$eventHandlers.get(name);
if (h) { if (handlers === undefined) {
h.find((val, idx, arr) => { return;
if (val !== callback) {
return false;
}
if (arr.length > 1) {
arr.splice(idx, 1);
} else {
delete this.$handler[event];
}
return true;
});
} }
handlers.find((item, index, array) => {
if (item !== fx) {
return false;
}
if (array.length > 1) {
array.splice(index, 1);
} else {
this.$eventHandlers.delete(name);
}
return true;
});
}; };
API.$fetch = {}; API.$fetch = {};