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.