dispatchEvent
The dispatchEvent()
function updates reactive state values programmatically. It supports both component-scoped state and shared application-level state using dynamic resolution. Automatically triggers reactivity updates and DOM sync.
Use Cases
- Trigger state updates outside of the original context
- Update deeply nested paths in state or shared state
- Use functional updates just like with
state()
setter - Supports scoped resolution (e.g., updates
user.name
in the right component)
Syntax
pphp.dispatchEvent('state.path', value); // or with a functional updater pphp.dispatchEvent('state.path', prev => prev + 1);
target
: A string path to the state key. Can be local (e.g.,user.name
) or shared (e.g.,app.user.name
).value
: The new value, or a function that receives the previous value and returns the new one.- Returns:
true
on successful update,false
if the path is invalid or an error occurred.
Example Usage
<p>User: {{ user.name }}</p>
<script>
const [user, setUser] = pphp.state({ name: "Guest" });
export const updateName = () => {
pphp.dispatchEvent('user.name', 'Jefferson');
};
export const capitalizeName = () => {
pphp.dispatchEvent('user.name', prev => prev.toUpperCase());
};
</script>
Shared State Example
<script>
// Assume shared state already exists
export const toggleDarkMode = () => {
pphp.dispatchEvent('app.theme', prev => prev === 'dark' ? 'light' : 'dark');
};
</script>
Note: If the path doesn’t match any declared state or shared key, an error is logged and no update is performed.
Behavior
- Automatically resolves scope hierarchy to locate the target state key.
- Supports updating nested paths like
form.user.name
. - Triggers reactivity — rerenders Mustache bindings and effects.
- Marks all nested fields dirty if the new value is an object.
- Handles shared state with
app.
prefix automatically. - Returns
false
if the target cannot be resolved or is not valid.