Add Event and EventTarget

master
Elias Fleckenstein 2021-08-06 23:19:34 +02:00
parent 2615778348
commit fa58e719d5
4 changed files with 65 additions and 5 deletions

View File

@ -1,7 +1,7 @@
# lua_async
This project aims to provide an API similar to the Node.js Event loop - for Lua, fully written in Lua itself. It is tested with Lua 5.1 and Lua 5.3.3, but should probably work with any Lua 5.x.
Note that the goal is not to clone the Node Event loop exactly.
This is already fully usable, but some features are missing (Events, EventTargets, some Promise methods) and will be implemented in the near future.
This is already fully usable, but some features are missing (especially some Promise methods) and will be implemented in the near future.
It also provides a few useful extra methods as well as basic scheduling.
## Current features

61
events.lua Normal file
View File

@ -0,0 +1,61 @@
local EventPrototype = {}
function EventPrototype:preventDefault()
self.defaultPrevented = true
end
function Event(type, data)
return setmetatable({
type = type,
data = data,
defaultPrevented = false,
timeStamp = os.clock(),
}, {__index = EventPrototype})
end
local EventTargetPrototype = {}
function EventTargetPrototype:dispatchEvent(event)
event.target = self
local callback = self["on" + event.type]
if callback then
callback(event)
end
local listeners = self.__eventListeners[type]
if listeners then
for i, callback in ipairs(listeners) do
callback(event)
end
end
return not event.defaultPrevented
end
function EventTargetPrototype:addEventListener(type, callback)
local listeners = self.__eventListeners[type] or {}
table.insert(listeners, callback)
self.__eventListeners[type] = listeners
end
function EventTargetPrototype:removeEventListener(type, callback)
local listeners = self.__eventListeners[type]
if listeners then
for k, v in pairs(listeners) do
if v == callback then
table.remove(listeners, k)
break
end
end
end
end
function EventTarget()
return setmetatable({
__eventListeners = {},
}, {__index = EventTargetPrototype})
end

View File

@ -26,6 +26,7 @@ return function(path)
"async_await",
"util",
"limiting",
"events",
} do
dofile(path .. f .. ".lua")
end

View File

@ -86,12 +86,10 @@ end
Promise = setmetatable({}, {
__call = function(_, resolver)
local promise = {
local promise = setmetatable({
state = "pending",
__children = {},
}
setmetatable(promise, {__index = PromisePrototype})
}, {__index = PromisePrototype})
if resolver then
resolver(