Skip to content

Instantly share code, notes, and snippets.

@Reselim
Created October 29, 2019 05:20
Show Gist options
  • Save Reselim/0de3ddebbcb214a6f86106c6a5f981bc to your computer and use it in GitHub Desktop.
Save Reselim/0de3ddebbcb214a6f86106c6a5f981bc to your computer and use it in GitHub Desktop.
shared()
local Event = require("Event")
local EventTree = {}
EventTree.__index = EventTree
function EventTree.new()
local self = setmetatable({
_downstreamEvent = Event.new(),
_upstreamEvent = Event.new()
}, EventTree)
self.Event = self._upstreamEvent
return self
end
function EventTree:DispatchEvent(eventName, ...)
self._upstreamEvent:Fire(eventName, ...)
end
function EventTree:HandleEvent(eventName, handler)
local function eventFilter(targetEventName, ...)
if targetEventName == eventName then
handler(...)
end
end
local downstreamConnection = self._downstreamEvent:Connect(eventFilter)
local upstreamConnection = self._upstreamEvent:Connect(eventFilter)
return function()
downstreamConnection:Disconnect()
upstreamConnection:Disconnect()
end
end
function EventTree:Derive(id)
local derivedEventTree = EventTree.new()
derivedEventTree.Parent = self
derivedEventTree._id = id
derivedEventTree._parentDownstreamConnection = self._downstreamEvent:Connect(function(eventName, targetId, ...)
if targetId == id then
derivedEventTree._downstreamEvent:Fire(eventName, ...)
end
end)
derivedEventTree._upstreamConnection = derivedEventTree._upstreamEvent:Connect(function(eventName, ...)
self._upstreamEvent:Fire(eventName, id, ...)
end)
return derivedEventTree
end
function EventTree:DisconnectFromParent()
assert(self.Parent, "This is a root EventTree!")
self._parentDownstreamConnection:Disconnect()
self._parentDownstreamConnection = nil
self._upstreamConnection:Disconnect()
self._upstreamConnection = nil
self.Parent = nil
self._id = nil
end
return EventTree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment