From 817387d7f2edd9d3414fb9ef9d0cca5df5708438 Mon Sep 17 00:00:00 2001 From: Starbeamrainbowlabs Date: Sun, 18 Sep 2022 15:57:23 +0100 Subject: [PATCH] Port EventEmitter from Node.js --- .../core/lib/EventEmitter.lua | 50 +++++++++++++++++++ worldeditadditions_core/init.lua | 2 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 worldeditadditions_core/core/lib/EventEmitter.lua diff --git a/worldeditadditions_core/core/lib/EventEmitter.lua b/worldeditadditions_core/core/lib/EventEmitter.lua new file mode 100644 index 0000000..17bb7fb --- /dev/null +++ b/worldeditadditions_core/core/lib/EventEmitter.lua @@ -0,0 +1,50 @@ + +--- A 3-dimensional vector. +-- @class +local EventEmitter = {} +EventEmitter.__index = EventEmitter +EventEmitter.__name = "EventEmitter" -- A hack to allow identification in wea.inspect + + +function EventEmitter.new() + local result = { + events = {} + } + setmetatable(result, EventEmitter) + return result +end + +function EventEmitter.addEventListener(this, event_name, func) + if this.events[event_name] == nil then this.events[event_name] = {} end + table.insert(this.events[event_name], func) +end +function EventEmitter.on(this, event_name, func) + return EventEmitter.addEventListener(this, event_name, func) +end + +function EventEmitter.removeEventListener(this, event_name, func) + if this.events[event_name] == nil then return false end + for index, next_func in ipairs(this.events[event_name]) do + if next_func == func then + table.remove(this.events[event_name], index) + break + end + end +end +function EventEmitter.off(this, event_name, func) + return EventEmitter.removeEventListener(this, event_name, func) +end + +function EventEmitter.emit(this, event_name, args) + if this.events[event_name] == nil then return end + for index,next_func in ipairs(this.events[event_name]) do + next_func(args) -- TODO: Move unpack compat to wea_c + end + -- TODO: Monitor execution time, log if it's slow? We'll need to move WEA utils over to wea_c first though... +end + +function EventEmitter.clear(this, event_name) + this.events[event_name] = nil +end + +return EventEmitter \ No newline at end of file diff --git a/worldeditadditions_core/init.lua b/worldeditadditions_core/init.lua index a8e616c..1c98dfe 100644 --- a/worldeditadditions_core/init.lua +++ b/worldeditadditions_core/init.lua @@ -27,7 +27,7 @@ wea_c.register_command = dofile(modpath.."/core/register_command.lua") wea_c.fetch_command_def = dofile(modpath.."/core/fetch_command_def.lua") wea_c.register_alias = dofile(modpath.."/core/register_alias.lua") wea_c.pos = dofile(modpath.."/core/pos.lua") - +wea_c.EventEmitter = dofile(modpath.."/core/lib/EventEmitter.lua") print("WEA_C pos", wea_c.pos.push) -- Initialise WorldEdit stuff if the WorldEdit mod is not present