Skip to content

Instantly share code, notes, and snippets.

@edude03
Created November 11, 2013 16:59
Show Gist options
  • Save edude03/7416482 to your computer and use it in GitHub Desktop.
Save edude03/7416482 to your computer and use it in GitHub Desktop.
//Create a function in which this demo will run.
(function() {
//The contructor for the dog class
function Dog() {}
//The "defaults" for the dog
Dog.prototype = {
//Define a default state for the dog
_state: "Sitting",
//Define a getter
get state() {
return this._state;
},
//Define a setter
set state(value) {
this._state = value;
var dog = this;
//When the dog's state changes call all the observers
//to notify them of the change
this.observers.forEach(function(observer) {
//This is an example of javascript scoping,
//Suprisingly to beginners, this is not the dog,
//But in the case the javascript engine
observer.call(this, dog);
})
},
//Functions that care that the dog is doing
observers: []
}
//Allows us to easily add observer
function registerObserver(fn, observe) {
observe.observers.push(fn);
}
//An example function we'll call when the dog is
function dogWatcher(dog) {
console.log("Oh look the dog is now %s", dog.state);
}
//With setup out of the way, lets make a dog
var dog = new Dog();
//Add a function that cares about the dog
registerObserver(dogWatcher, dog);
//Change the dog's state
dog.state = 'Walking';
dog.state = 'Playing';
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment