Skip to content

Instantly share code, notes, and snippets.

@ear
Created August 16, 2015 12:23
Show Gist options
  • Save ear/bc658adde0c864dfa01d to your computer and use it in GitHub Desktop.
Save ear/bc658adde0c864dfa01d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="UTF-8"></meta>
<script>
/* Object.defineProperty (works in all browsers)
*
* It lets us define exactly one function that runs when a particular object's
* property is about to be read, as well as define exacly one function that runs
* when that object's property is about to be changed.
*
* We can use it to change the behavior of such actions as well as triggers for
* extra code we would like to run every time one of the two things is going to
* happen.
*/
var prop = 0; // the actual value storage
var obj = {}; // an empty object
// define the property 'prop' on the object obj
Object.defineProperty(obj, 'prop', {
// when read, it runs this function, and returns the backing value
get: function () {
console.log('obj.prop is being read! obj.prop =', prop);
return prop;
},
// when written to, it runs this other function, changing the backing value
set: function (value) {
console.log('obj.prop is being changed! obj.prop =', value,
'(', 'previously obj.prop =', prop, ')');
prop = value;
}
});
// some tests
console.log('HELLO WHAT IS OBJ.PROP?', obj.prop);
console.log('CHANGING IT TO 2');
obj.prop = 2;
console.log('HOW ABOUT NOW?!', obj.prop);
</script>
<!DOCTYPE html>
<meta charset="UTF-8"></meta>
<script>
/* Object.observe (works in Chrome and Opera only)
*
* It lets us define a function that runs after an object changed.
* This function is passed a time-ordered list of changes.
*
* Each object in this list represents a change in the form of:
* {
* name: 'prop', // name of the changed property
* type: 'update', // or 'add' and 'delete' for list elements
* oldValue: …, // the old value of the property
* object: … // the new object after the change was made
* }
*/
var obj = {
'prop': 0
};
Object.observe(obj, function (changes) {
console.log('Object.observe triggered with the following list of changes:')
console.log(changes);
changes.forEach(function (change) {
if (change.type == 'update') {
console.log('obj.prop has been changed! obj.prop =',
change.object.prop,
'(', 'previously obj.prop =', change.oldValue, ')');
}
});
});
// some tests
console.log('HELLO WHAT IS OBJ.PROP?', obj.prop);
console.log('CHANGING IT TO 2');
obj.prop = 2;
console.log('HOW ABOUT NOW?!', obj.prop);
// obj.prop = 3;
// obj.prop = 4;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment