mirror of
https://github.com/littensy/charm.git
synced 2026-10-21 11:44:08 +00:00
feat: add effect cleanups, add docs (#2)
* docs: update readme * feat: add cleanup function to effects * refactor: move peek function to store module * test: add nested atom check * docs: add doc comments * fix: `effect()` type * refactor: remove divider comment
This commit is contained in:
parent
1a65a4a0de
commit
6a9c580bd7
24 changed files with 805 additions and 76 deletions
|
|
@ -1,10 +1,26 @@
|
|||
local store = require(script.Parent.store)
|
||||
|
||||
local function effect(molecule: () -> nil): () -> ()
|
||||
local captured = store.capture(molecule)
|
||||
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 function listener()
|
||||
molecule()
|
||||
if cleanup then
|
||||
cleanup()
|
||||
end
|
||||
|
||||
cleanup = callback()
|
||||
end
|
||||
|
||||
for atom in captured do
|
||||
|
|
@ -15,7 +31,11 @@ local function effect(molecule: () -> nil): () -> ()
|
|||
for atom in captured do
|
||||
store.listeners[atom][listener] = nil
|
||||
end
|
||||
|
||||
if cleanup then
|
||||
cleanup()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return effect
|
||||
return effect :: (callback: (() -> ()) | (() -> Cleanup)) -> Cleanup
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue