Skip to content

Instantly share code, notes, and snippets.

@Traineratwot
Created March 2, 2024 09:36
Show Gist options
  • Save Traineratwot/df1a19f73b2207a3e527f4a0e0563fde to your computer and use it in GitHub Desktop.
Save Traineratwot/df1a19f73b2207a3e527f4a0e0563fde to your computer and use it in GitHub Desktop.
TwoWayBinding
class TwoWayBinding {
  private inputElement: HTMLInputElement;
  private data: { [key: string]: any };

  constructor(inputSelector: string, data: { [key: string]: any }, propertyName: string) {
    // Save the reference to the data object
    this.data = data;

    // Find and save the input element
    this.inputElement = document.querySelector(inputSelector) as HTMLInputElement;

    // Set the initial value of the input to the value from the data object
    this.inputElement.value = data[propertyName];

    // Listen for changes on the input and update the data object
    this.inputElement.addEventListener('input', (event) => {
      const target = event.target as HTMLInputElement;
      this.data[propertyName] = target.value;
    });

    // Define a setter and getter for the property that will update the input
    Object.defineProperty(this.data, propertyName, {
      get: () => {
        return this.inputElement.value;
      },
      set: (value) => {
        this.inputElement.value = value;
      }
    });
  }
}

const data = { text: 'Initial value' };
const twb = new TwoWayBinding('#myInput', data, 'text');

HTML:

<input type="text" id="myInput">

Please ensure that the TypeScript transpilation settings allow for DOM manipulation, and that your HTML contains an element with the corresponding ID to select.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment