Javascript Generation - A Change Of Heart

02 Apr 2008

I've previously talked about my dislike for code generation in Javascript. I still standby that, but I am beginning to have a change of heart for certain scenarios. I've been working on a couple of ExtJS applications recently and I've got lots of code which is purely ExtJS stuff on its own - no HTML or other code in there really. It's been a project where I've been using C# 3 and it's partly the similarities between the two languages which have triggered this rethink.

Take a look at this code:

var win = new Ext.Window({
	title: 'Order Viewer', layout: 'border',
	width: 500, height: 500,
	modal: true, resizable: false, closable: false, draggable: false,
	items: [ frm, lst ]

win.on('render', function() {

That's pretty standard stuff for what I'm doing with Ext right now - I create a new window with a load of configuration options, then add in an event handler for the window's render event, and finally show the window on screen. Now imagine that you could write the following in C# 3:

var win = new Ext.Window{
	Title = "OrderViewer", Layout = Layout.Border,
	Width = 100, Height = 200,
	Modal = true, Resizable = false, Closable = false, Draggable = false,
	Items = new [] { frm, lst }

win.Render += delegate {

As far as I'm aware, all of the above is valid C# 3 code. I've basically written it as I'd like to use it, with an enum for the Layout type, and C# style event handler syntax, but the interesting thing to me is how very similar it is to the Javascript version.

The ExtSharp project allows you to write your Ext code in C# and have it rendered as Javascript. I'm going to explore it in my next post, and examine how closely it can be made to fit the code sample above.