Skip to content
fabiantheblind edited this page Mar 13, 2014 · 1 revision

The Object Watch function is pretty awesome. You can add a watch function to any property of an object. If that property changes your function gets executed.

 //        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 //                    Version 2, December 2004
 
 // Copyright (C) 2014 Fabian "@fabiantheblind" Morón Zirfas
 
 // Everyone is permitted to copy and distribute verbatim or modified
 // copies of this license document, and changing it is allowed as long
 // as the name is changed.
 
 //            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 //   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
 //  0. You just DO WHAT THE FUCK YOU WANT TO.
 
 
// Object.watch()  Mozilla Firefox Only.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
//
// Node.js throws an error TypeError: Object #<Object> has no method 'watch'
//
// Works in Adobe Extendscript (woohoo!\o/)
 
// this test if we are in extendscript or not
if(typeof $ === 'undefined'){
  // does not exist
  console.log('This is a browser');
}else{
    $.writeln('This is Extedscript. Creating console.log function');
var console = {
  log: function(msg) {
    $.writeln(msg);
  }
};
 
}
 
// logger function
var logger = function(prop, oldval, newval) {
  console.log("This is object: " + prop + " Old Value: " + oldval + " New Value:" + newval);
 
};
 
// create a simple object
var obj = {
  a: 2,
  b: 3,
  c: true
};
 
// assign a function to all of them
for (var key in obj) {
  obj.watch(key, logger);
}
 
 
// This also only works in ExtendScript
//   obj.watch(["a","b","c"], function(prop, oldval, newval) {
//   console.log("This is object: " + prop + " Old Value: " + oldval + " New Value:" + newval);
// });
 
 
obj.a = 5;
 
obj.c = false;
 
obj.b = null;
 
obj.b = []; // <-- This works in ExtendScript and fails in Firefox
 
obj.b.push(1);
 
obj.a = obj.b[0];
 
// awesome

Clone this wiki locally