DOM Element Property Observer
An example of how to observe and react to changes in DOM elements
HTML
<p id="text">Any text yortrtu like</p>
JavaScript
//1. Get a reference to the DOM element
var text = document.querySelector("#text");
//2. Create a data object to store DOM values
var data = {
text: undefined,
initialize: function (config) {
this.text = config.text;
}
};
//3. Load the text into the data object
data.initialize({
text: text.innerHTML
});
//4. Start observing the text property on the data object
//Arguments: the object you want to observe, the property as a string,
//and the name of the callback handler, bound to this scope
observe(data, "text", callbackHandler.bind(this));
//5. Create a custom callback handler that runs whenever an observed property changes
//You can have one callback for all your properties, or create unique callbacks
//for each property or subject
function callbackHandler(subject, property) {
if (subject === data && property === "text") {
//Notify the console that the property has been changed
console.log("data." + property + ": " + subject[property]);
//Update the DOM element with the new value
text.innerHTML = subject[property];
}
}
//6. Check if it works
//Change the text value in the data object - the DOM will refresh automatically
text.innerHTML = "The DOM text has been changed";
//THE OBSERVE FUNCTIONS
//A function to modify the property's getters and
//setters so that a custom callback handler can be run in the main
//program each time the property is changed
function observe(subject, property, callbackHandler) {
Object.defineProperty(subject, property, {
//Return the default value of the property
//("value" automatically gives you the property's current value)
get: function () {
return value;
},
//Set the property with a new value
set: function (newValue) {
//Assign the new value
value = newValue;
//Bind the observer's changeHandler to the subject
subject.changeHandler =...