Skip to content

Commit

Permalink
Refactor addEvent() to forward events rather than take callbacks
Browse files Browse the repository at this point in the history
Instead of addEvent creating the event on the zone and calling a callback when the event is triggered and the player is in the zone, it instead creates a middleman event that forwards the arguments from the event trigger to the real event if the player is in the zone.

So you would call addEvent("test") and that would create an internal event that would call the "test" event if the player was in the zone when the event was triggered. That way, you can just add an event handler anywhere in the code to catch that "test" event.
  • Loading branch information
mkafrin committed Dec 21, 2020
1 parent 29f4849 commit 1c0c3fc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
22 changes: 12 additions & 10 deletions client.lua
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
eventPrefix = '__PolyZone__:'
PolyZone = {}

local defaultColorWalls = {0, 255, 0}
local defaultColorOutline = {255, 0, 0}
local defaultColorGrid = {255, 255, 255}

PolyZone = {}

-- Utility functions
local abs = math.abs
local function _isLeft(p0, p1, p2)
Expand Down Expand Up @@ -547,20 +548,21 @@ function PolyZone:onPlayerInOut(onPointInOutCb, waitInMS)
self:onPointInOut(PolyZone.getPlayerPosition, onPointInOutCb, waitInMS)
end

function PolyZone:addEvent(name, cb)
function PolyZone:addEvent(eventName)
if self.events == nil then self.events = {} end
RegisterNetEvent(name)
self.events[name] = AddEventHandler(name, function (...)
local internalEventName = eventPrefix .. eventName
RegisterNetEvent(internalEventName)
self.events[eventName] = AddEventHandler(internalEventName, function (...)
if self:isPointInside(PolyZone.getPlayerPosition()) then
cb(...)
TriggerEvent(eventName, ...)
end
end)
end

function PolyZone:removeEvent(name)
if self.events and self.events[name] then
RemoveEventHandler(self.events[name])
self.events[name] = nil
function PolyZone:removeEvent(eventName)
if self.events and self.events[eventName] then
RemoveEventHandler(self.events[eventName])
self.events[eventName] = nil
end
end

Expand Down
6 changes: 4 additions & 2 deletions server.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
function triggerZoneEvent(name, ...)
TriggerClientEvent(name, -1, ...)
local eventPrefix = '__PolyZone__:'

function triggerZoneEvent(eventName, ...)
TriggerClientEvent(eventPrefix .. eventName, -1, ...)
end

RegisterNetEvent("PolyZone:TriggerZoneEvent")
Expand Down

0 comments on commit 1c0c3fc

Please sign in to comment.