Metaprogramming in JavaScript: Auto properties for ASP.NET AJAX
October 8th, 2007
Sometimes, large company is no better than several independent companies.
I always get this thought when looking at ASP.NET AJAX property accessors.
For people not familiar with the matter:
Microsoft ASP.NET AJAX requires developer to use property accessors to encapsulate javascript fields.
This would be a great idea, if only Microsoft IE supported javascript getters and setters.
Mozilla supports them, and Opera will in 9.50, but IE does not (they are not standard).
Also, IE does not have any hacky way to achieve the same effect (except in VBScript, which seems to be limited).
So in ASP.NET AJAX each property requires two functions named get_propertyName and set_propertyName.
Fortunately, javascript is very powerful in class member manipulation.
So I do not have to write things like this:
MyControl.prototype = { get_text : function() { return this._text; }, set_text : function(value) { this._text = value; } }
And I do not have to wait for auto properties as it is the case for C#.
Instead I just made an helper object named Auto and do things this way:
MyControl.prototype = {…} Auto.properties(MyControl.prototype, [ 'text', 'value', … ]);
Code for this helper can be very simple.
(in actual project I have additional complexity like Auto support for INotifyPropertyChanged).
var Auto = { property : function(prototype, name) { var getter = function() { return this['_' + name]; }; prototype['get_' + name] = prototype['get_' + name] || getter; var setter = function(value) { this['_' + name] = value; }; prototype['set_' + name] = prototype['set_' + name] || setter; }, properties : function(prototype, names) { names.forEach(function(name) { Auto.property(prototype, name); }); } }
This also requires forEach method on Array, but that one is pretty obvious.
I like to show this code when I hear about Javascript being assembly language and whatever-to-javascript compilation.