After playing with angular for a while I got curios about how it can watch for variable changes and execute a function when these occur.

I did a little research and found out that all watches that you define in Angular are evaluated by an event loop that is entered when some event is triggered or apply is called.

That didn’t sound very interesting to me, but I did find some interesting alternatives.


This method allows you to define a property in an object that(among other things) will call a setter or a getter when you try to get or set a variable. Here is how it works:

var a = {};
Object.defineProperty(a, 'watched', {
  get: function() {
    return this.value;
  set: function(val) {
    this.value = val;

My example is very ugly but it does show you how the get method and the set method work. This is interesting because every time you do something like:

a.watched = 5;

The set function gets called(“magic” is logged in the console) so you can here put any bindings you might need. Eli grey used this technique to create a polyfill for the watch method currently only supported by Gecko.

The future

Since this has been considered a very useful feature, a similar technique is being proposed for ECMAScript 7. The formal definition hasn’t been finalized but you can find a very good introduction to it by Addy Osmani in his article: Data-binding Revolutions with Object.observe()

[ design_patterns  javascript  programming  ]
Mutexes in C++ design_patterns programming
Passing by reference to a thread in C++ design_patterns programming
Sorting algorithms javascript programming
Futures, async, packaged_tasks and promises in C++ design_patterns programming
C++ Header files  design_patterns programming