Listener
Watcher is a feature in ofa.js used to listen for data changes and execute corresponding logic. When reactive data changes, the watcher automatically triggers a callback function, allowing you to perform tasks such as data transformation, side effects operations, or asynchronous processing.
Basic Usage
Listeners are defined in the component's watch object, where the key corresponds to the name of the data property to be observed, and the value is the callback function executed when the data changes.
count:{{count}}
doubleCount:{{doubleCount}}
Callback Function Parameters
The listener callback function receives two parameters:- newValue: the new value after the change
{watchers}: all watcher objects of the current component
After data changes, debounce processing will be performed first, and then the callback in watch will be executed; the watchers parameter is the set of all merged changes within this debounce cycle.
The functions in watch are called immediately after the component is initialized, used to establish data watchers. You can distinguish whether it's the first call by checking if watchers has any length.
Name: {{name}}
Age: {{age}}
{{log}}
Deep Watch
For nested data of object or array types, watch will automatically perform deep listening.
User Info:
Name: {{user.name}}
Age: {{user.age}}
Hobbies: {{user.hobbies.join(', ')}}
Listening to Multiple Data Sources
You can listen for changes in multiple pieces of data simultaneously and execute corresponding logic in the callback function based on the changes of multiple data.
Width: {{rectWidth}}
Height: {{rectHeight}}
Area: {{area}}
Actual Application Scenarios
1. Form Validation
{{usernameError}}
{{emailError}}
2. Setting the Theme
Settings: {{settings.theme}}
Save Status: {{saveStatus}}
Precautions
- Avoid modifying watched data: Modifying the data being watched in a watcher callback may cause an infinite loop. If modification is necessary, ensure proper conditional checks.
- Consider using computed properties instead: If you need to calculate a new value based on changes in multiple data, it is recommended to use computed properties instead of watchers.