How does JS monitor a variable change?

JavaScript is a popular programming language used for web development and creating interactive web applications. In JavaScript, you can use event listeners to capture variable changes and perform corresponding operations when the variable changes. This article will introduce how to use JavaScript to monitor variable changes, and how to use event listeners to trigger corresponding operations.

Monitor variable changes

In JavaScript, you can use a technique called "observer mode" to monitor changes in variables. Observer mode is a design pattern used to establish a one-to-many dependency relationship between objects, so that when the state of an object changes, all objects that depend on it can be automatically notified and update themselves status.

In JavaScript, you can define an "observer" object and register it to a "subject" object, so that when the state of the subject object changes, the observer object can receive notifications and perform corresponding operations. Here is a simple example:

class Subject {
  constructor() {
    this.observers = [];
    this.state = null;
  }

  addObserver(observer) {
    this.observers.push(observer);
  }

  removeObserver(observer) {
    this.observers = this.observers.filter(o => o !== observer);
  }

  setState(state) {
    this.state = state;
    this.notifyObservers();
  }

  notifyObservers() {
    this.observers.forEach(observer => observer.update(this.state));
  }
}

class Observer {
  constructor() {
    this.state = null;
  }

  update(state) {
    this.state = state;
    console.log(`Observer received state update: ${state}`);
  }
}

const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.setState('foo');
subject.setState('bar');

subject.removeObserver(observer2);

subject.setState('baz');

In the above example, we defined a subject object Subject, which has an observersarray for storing observer objects registered to it. SubjectAn object also has a stateproperty that stores its state. SubjectThe object has three methods:

  • addObserver(observer): Register an observer object into observersthe array.
  • removeObserver(observer): observersRemoves an observer object from the array.
  • setState(state): Set statethe value of the property, and call notifyObservers()the method to notify all registered observer objects.
  • notifyObservers(): Iterates through observersthe array and calls update()the methods of each observer object, statepassing them the value of the property as a parameter.

We also define an observer object Observerwhich has a stateproperty to store the state of the subject object. ObserverThe object has a update(state)method that receives status updates for the subject object and prints the updated status to the console.

In the above example, we created two observer objects observer1and observer2registered them both subjectwith the subject object. Then, we call subject.setState()the method, passing three parameters 'foo', , 'bar'and , respectively. 'baz'Whenever a method is called setState(), Subjectthe object updates its state and notifies all registered observer objects. When Observeran object receives a state update, it prints the updated state to the console.

In the above example, we manually called setState()the method to update the state of the theme object. But in practical applications, we usually update the state automatically during the running of the program. For example, in a web application, when a user fills out a form, the values ​​of the form may change at any time, we need to listen for changes in these values ​​and update the state of the application when a change occurs.

In JavaScript, you can use an object called "Proxy" to monitor changes in object properties. ProxyObjects allow us to define an "interceptor" that intercepts access and modification of properties of the target object, and performs corresponding operations when accessing or modifying properties. The following is an example of using an Proxyobject to monitor object property changes:

const target = { foo: 'bar' };

const handler = {
  get(target, prop) {
    console.log(`Getting ${prop} = ${target[prop]}`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Setting ${prop} = ${value}`);
    target[prop] = value;
  }
};

const proxy = new Proxy(target, handler);

proxy.foo; // logs "Getting foo = bar"
proxy.foo = 'baz'; // logs "Setting foo = baz"

In the above example, we defined an targetobject that has a fooproperty with an initial value of 'bar'. We also define an handlerobject with two methods:

  • get(target, prop): Intercept targetaccess to object properties and print logs when properties are accessed.
  • set(target, prop, value): Intercept targetmodification of object properties and print logs when properties are modified.

We create an proxyobject, targetpass the object to it as a parameter, and handlerpass the object to it as the second parameter. When we use proxy.foothe access fooproperty, the method handlerof the object get()will be called and the log will be printed. When we use proxy.foo = 'baz'the modified fooproperty, the method handlerof the object set()will be called and the log will be printed.

In practical applications, we can targetreplace the object with a variable that needs to monitor changes, handlerreplace the object with a custom interceptor object, and perform corresponding operations in the get()sum method of the interceptor object.set()

Use event listeners to trigger actions

In addition to listening to variable changes, JavaScript also provides an event listener mechanism that can trigger actions when specific events occur. For example, in a web application, when a user clicks a button or submits a form, you can use event listeners to trigger the corresponding action.

JavaScript provides a set of built-in events, such as click, submit, keydownetc., which can listen to these events and trigger actions when the event occurs. For example, the following code demonstrates how to use addEventListener()methods to listen for clickevents on buttons:

const button = document.getElementById('myButton');

button.addEventListener('click', () => {
  console.log('Button clicked');
});

In the above example, we use document.getElementById()the method to get a idbutton myButtonelement, and then use addEventListener()the method to listen to the button's clickevent. When the user clicks the button, console.log()the method prints a message to the console.

In addition to built-in events, JavaScript also supports custom events. We can use Eventobjects and CustomEventobjects to create custom events and use dispatchEvent()methods to trigger events. The following code demonstrates how to create and trigger a custom event:

const myEvent = new CustomEvent('my-event', {
  detail: { message: 'Hello, world!' }
});

window.dispatchEvent(myEvent);

In the above example, we created a my-eventcustom event called and detailpassed an object containing the message in the property. Then, we use window.dispatchEvent()the method to trigger this event. Methods can be used addEventListener()to listen to custom events and perform corresponding actions when the event occurs.

in conclusion

JavaScript provides a variety of ways to monitor variable changes, such as using the observer pattern, using Proxyobjects, and using event listeners. These methods can help us monitor changes in variables in real time and perform corresponding actions when variables change. In practical applications, we need to choose an appropriate method of monitoring variable changes according to specific needs, and write the corresponding code to achieve it.

Guess you like

Origin blog.csdn.net/tyxjolin/article/details/130072208