3. Use Events
You can check the state value change through re-rendering in react, watchEffect in vue, and $ in svelte.
If you don't use state, re-rendering won't happen.
In addition, events are provided with a lot of information including status.
Set the events to be exposed through the setEvents function.
You just need to tell how to register the event through on.
If you want to trigger an event manually without using on, use emit function.
The following code changes the width and height values when the window size is changed.
import { reactive } from "@cfcs/core";
const REACTIVE_ADAPTER = ({ setEvents, on, emit, onInit, onDestroy }) => {
setEvents(["resize"]);
const obj = reactive({
width: 0,
height: 0,
});
const onResize = e => {
obj.width = window.innerWidth;
obj.height = window.innerHeight;
// If you don't use the `on` function, manually trigger the event via `emit`.
// emit("resize", e);
};
on((eventName, callback) => {
// register
window.addEventListener(eventName, callback);
return () => {
// unregister
window.removeEventListener(eventName, callback);
};
});
onInit(() => {
window.addEventListener("resize", onResize);
});
onDestroy(() => {
window.removeEventListener("resize", onResize);
});
return obj;
};
Frameworks
Events in the framework can be used as calls with an on prefix and a name in camelcase format.
ex) resize => onResize
onResize(() => {});
- React
- Vue@2
- Vue@3
- Svelte
The second parameter of an event in React is a dependency array, a usage similar to `useEffect`.
import { useReactive } from "@cfcs/react";
export function App() {
const {
width,
height,
onResize,
} = useReactive(REACTIVE_ADAPTER);
onResize(e => {
// https://developer.mozilla.org/en-US/docs/Web/API/UIEvent
console.log(e);
}, []);
return <div>{width}x{height}</div>;
}