/
BoundAncestorTracker.lua
71 lines (56 loc) · 1.63 KB
/
BoundAncestorTracker.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
--[=[
Tracks a parent bound to a specific binder
@class BoundAncestorTracker
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local ValueObject = require("ValueObject")
local BinderUtils = require("BinderUtils")
local BoundAncestorTracker = setmetatable({}, BaseObject)
BoundAncestorTracker.ClassName = "BoundAncestorTracker"
BoundAncestorTracker.__index = BoundAncestorTracker
--[=[
Constructs a new BoundAncestorTracker
@param binder Binder<T>
@param child Instance
@return BoundAncestorTracker
]=]
function BoundAncestorTracker.new(binder, child)
local self = setmetatable(BaseObject.new(), BoundAncestorTracker)
self._child = child or error("No child")
self._binder = binder or error("No binder")
--[=[
@prop Class ValueObject<T>
@readonly
@within BoundAncestorTracker
Bound value
]=]
self.Class = ValueObject.new()
self._maid:GiveTask(self.Class)
-- Handle instance removing
self._maid:GiveTask(self._binder:GetClassRemovingSignal():Connect(function(class)
if class == self.Class.Value then
self.Class.Value = nil
end
end))
self._maid:GiveTask(self._binder:GetClassAddedSignal():Connect(function(_, instance)
if self._child:IsDescendantOf(instance) then
self:_update()
end
end))
-- Perform update
self._maid:GiveTask(self._child.AncestryChanged:Connect(function()
self:_update()
end))
self:_update()
return self
end
function BoundAncestorTracker:_update()
local parent = self._child.Parent
if not parent then
self.Class.Value = nil
return
end
self.Class.Value = BinderUtils.findFirstAncestor(self._binder, parent)
end
return BoundAncestorTracker