Understanding On Change A Comprehensive Guide with Dozens of API Examples

Understanding on-change: A Comprehensive Guide with Dozens of API Examples

The on-change function provides a robust way to track and respond to changes in objects and arrays in JavaScript. It’s an essential tool for both frontend and backend developers who need to monitor changes in their application state. In this guide, we will introduce the on-change API and explore its diverse functionalities with illustrative code snippets and a practical app example using the explained APIs.

Introduction to on-change

The on-change library listens for changes to objects and arrays, providing a callback whenever a change is detected. This is very useful for applications that need to react to state changes dynamically.

Installing the Library

  
  npm install on-change
  

Basic Usage

Here’s a simple example of how to use on-change:

  
  const onChange = require('on-change');

  const object = {
    foo: 'bar'
  };

  const watchedObject = onChange(object, function (path, value, previousValue) {
    console.log('Object changed:', path, value, previousValue);
  });

  watchedObject.foo = 'baz'; // Console: Object changed: foo baz bar
  

Tracking Array Changes

  
  const array = [1, 2, 3];

  const watchedArray = onChange(array, function (path, value, previousValue) {
    console.log('Array changed:', path, value, previousValue);
  });

  watchedArray.push(4); // Console: Array changed: 3 4 undefined
  

Nested Objects

  
  const nestedObject = {
    a: {
      b: {
        c: 'd'
      }
    }
  };

  const watchedNestedObject = onChange(nestedObject, function (path, value, previousValue) {
    console.log('Nested object changed:', path, value, previousValue);
  });

  watchedNestedObject.a.b.c = 'e'; // Console: Nested object changed: a.b.c e d
  

Removing Listeners

  
  const object = { a: 1, b: 2 };

  const watchedObject = onChange(object, function (path, value, previousValue) {
    console.log('Object changed:', path, value, previousValue);
  });

  onChange.unsubscribe(watchedObject);

  watchedObject.a = 2; // No log output
  

Comprehensive App Example

Below is a practical example where the on-change library is used to create a simple state management system in a To-Do application.

HTML Structure

  
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To-Do App</title>
  </head>
  <body>
    <h1>To-Do List</h1>
    <ul id="todo-list"></ul>
    <input type="text" id="new-todo" placeholder="Enter a new to-do">
    <button id="add-todo">Add To-Do</button>

    <script src="app.js"></script>
  </body>
  </html>
  

JavaScript (app.js)

  
  const onChange = require('on-change');

  // State object
  const state = {
    todos: []
  };

  // Watch state
  const watchedState = onChange(state, function (path, value) {
    if (path === 'todos') {
      renderTodos();
    }
  });

  // Render function
  function renderTodos() {
    const todoList = document.getElementById('todo-list');
    todoList.innerHTML = '';
    watchedState.todos.forEach(todo => {
      const li = document.createElement('li');
      li.textContent = todo;
      todoList.appendChild(li);
    });
  }

  // Add to-do function
  document.getElementById('add-todo').addEventListener('click', () => {
    const newTodo = document.getElementById('new-todo').value;
    if (newTodo) {
      watchedState.todos.push(newTodo);
      document.getElementById('new-todo').value = '';
    }
  });

  renderTodos();
  

This example demonstrates how the on-change library can monitor the to-dos array. Whenever a new to-do is added, the render function updates the DOM to display the new to-do item.

Conclusion

The on-change library is an incredibly powerful tool for detecting changes in objects and arrays. The examples provided demonstrate just a few of the many possibilities. By integrating this library, developers can create more dynamic and responsive applications.

Hash: edc16f96dc0ae93827c129bbb1108e285853e77afef2578b15ff36714aedb405

Leave a Reply

Your email address will not be published. Required fields are marked *