Make changed() run initially

This commit is contained in:
Aaron Smith 2023-09-28 16:46:32 +01:00
parent 46937c6979
commit c03fb05779
4 changed files with 24 additions and 1 deletions

View file

@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Reactive scopes created within reactive scopes are now destroyed on rerun. - Reactive scopes created within reactive scopes are now destroyed on rerun.
- `untrack()` can be called outside of reactive scopes. - `untrack()` can be called outside of reactive scopes.
- `changed()` will also run its callback with the initial property value.
### Fixed ### Fixed

View file

@ -154,3 +154,23 @@ instances.
changed("Text", output) changed("Text", output)
} }
``` ```
## changed()
A wrapper for `action()` to listen for property changes.
- **Type**
```lua
function changed(property: string, callback: (...unknown) -> ()): Action
```
- **Details**
Will run the given callback any time the property is changed, as well as
when the action is initially run.
The changed connection is disconnected when the reactive scope the action is
ran in is destroyed.
Runs with an action priority of 1.

View file

@ -12,6 +12,8 @@ local function changed<T>(property: string, callback: (T) -> ())
cleanup(function() cleanup(function()
con:Disconnect() con:Disconnect()
end) end)
callback((instance :: any)[property])
end) end)
end end

View file

@ -1806,7 +1806,7 @@ TEST("changed()", wrap_root(function()
changed("Text", output) changed("Text", output)
} }
--CHECK(output() == "a") CHECK(output() == "a")
text.Text = "b" text.Text = "b"
CHECK(output() == "b") CHECK(output() == "b")
end end