mirror of
https://github.com/littensy/charm.git
synced 2026-10-21 03:36:11 +00:00
feat: allow conditional dependencies (#4)
* feat: allow conditional dependencies * docs: remove conditional deps warnings * fix: allow nested captures * docs: add dev flag * fix: `try()` uses pcall if passed `finally()` * docs: interval is optional * docs: update readme * docs: add client/server tags
This commit is contained in:
parent
fbc86d22c6
commit
a90d131fed
14 changed files with 290 additions and 98 deletions
|
|
@ -6,31 +6,24 @@ type Cleanup = () -> ()
|
|||
Runs the given callback immediately and whenever any atom it depends on
|
||||
changes. Returns a cleanup function that unsubscribes the callback.
|
||||
|
||||
Note that dependencies are only evaluated once when the effect is created,
|
||||
and conditional dependencies may not work as expected.
|
||||
|
||||
@param callback The function to run.
|
||||
@return A function that unsubscribes the callback.
|
||||
]=]
|
||||
local function effect(callback: () -> any): () -> ()
|
||||
local captured, cleanup = store.capture(callback)
|
||||
local dependencies, cleanup = store.capture(callback)
|
||||
|
||||
local function listener()
|
||||
if cleanup then
|
||||
cleanup()
|
||||
end
|
||||
|
||||
cleanup = callback()
|
||||
dependencies, cleanup = store.reconnect(callback, dependencies, listener)
|
||||
end
|
||||
|
||||
for atom in captured do
|
||||
store.listeners[atom][listener] = true
|
||||
end
|
||||
store.connect(dependencies, listener)
|
||||
|
||||
return function()
|
||||
for atom in captured do
|
||||
store.listeners[atom][listener] = nil
|
||||
end
|
||||
store.disconnect(dependencies, listener)
|
||||
|
||||
if cleanup then
|
||||
cleanup()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue