Property Observer

An example of how to observe property changes on JavaScript objects

HTML

<p id="output">

JavaScript

//This is an example of how to observe property changes on JavaScript objects.

var output = document.querySelector("#output");

//1. Create a an object with a few properties
//This is the "subject" that you're going to observe

var subject = {
    x: 1,
    y: 56,
    name: "",
};

//2. Create two subjects
var subjectOne = Object.create(subject);
subjectOne.name = "subjectOne";
var subjectTwo = Object.create(subject);
subjectTwo.name = "subjectTwo";

//3.Create A custom function called a callback handler that runs 
//whenever an observed property changes. You can have one callback 
//handler for all your properties, or create unique ones for each property or subject

function callbackHandler(subject, property) {
    //Any special actions that your program should take when this property 
    //changes can be added here. These can become as complex as you need them to be

    //Here's how to display the subject and its new property value
    output.innerHTML += subject.name + " " + property + ": " + subject[property] + "<br>";

    //Here's how to find a specific subject and proprerty
    //a. Find out if subject changed any of its properties
    if (subject === subjectTwo) {
        output.innerHTML += "A property changed on subjectTwo" + "<br>"

        //b. Do something if a specific property you're observing changes
        if (property === "y") {
            output.innerHTML += "Its y property changed" + "<br>"
        }
    }
}

//4. Start observing subjectOne's x and y properties
observe(subjectOne, "x", callbackHandler.bind(this));
observe(subjectOne, "y", callbackHandler.bind(this));

//5. Start observing subjectTwo's x and y properties
observe(subjectTwo, "x", callbackHandler.bind(this));
observe(subjectTwo, "y", callbackHandler.bind(this));

//6. Change their properties and check if we can observe the changes in the console
subjectOne.x = 9;
subjectOne.y = 3;
subjectTwo.x = 100;
subjectTwo.y = 250;

//7. Unobserve subjectOne.x
unobserve(subjectOne,...