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.

defineProperty

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:

1
2
3
4
5
6
7
8
9
10
var a = {};
Object.defineProperty(a, 'watched', {
  get: function() {
    return this.value;
  },
  set: function(val) {
    console.log('magic');
    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:

1
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  ]
Dependency injection (Inversion of Control) in Spring framework
Flyway - Version control for Databases in Java
Immutables and Java
Introduction to JDBI
Introduction to JDBC