Client-Side JavaScript DSLs
This blog post is about solving one of my JavaScript paint points; specifically its verbosity when defining inline functions. The way in which I solve it is interesting to me and hopefully to someone else too.
Here goes…
Why not do DSLs on the client side by compiling to JavaScript in a compiler written in JavaScript?
I realize that doing a “true compiler” is computationally expensive, but the leaps in JavaScript performance we’ve seen lately make it tractable.
To do the job with the respect it deserves, you need to build a full parse tree, but for my particular DSL, a replacement scheme that relies on regular expressions should do fine except in the pathological cases. Except for obfuscated code, I have yet to find a piece of code that uses commas to separate expressions for example.
So, what do I have in mind?
I love the JavaScript language, but its format for defining lambda expressions is nasty. You’re forced to insert the function keyword where (except for pathological cases) it could be inferred from its context. This wouldn’t bother me at all if I wasn’t required to define them so often while working with jQuery.
For those who are visual, this is the code I’d like to write:
<script type="text/x-javascript"> $({ alert("Hello"); $("a").click((e) { alert("clicked"); }); $.post("testing.php", {a: 100, b:100}, (result) { alert("Result is: " + result); }); }); </script>
And this is the code I have to write right now:
<script type="text/javascript"> $(function() { alert("Hello"); $("a").click(function (e) { alert("clicked"); }); $.post("testing.php", {a: 100, b:100}, function(result) { alert("Result is: " + result); }); }); </script>
Now, it’s not a big change, but it’s definitely worth it as your jQuery lambda heavy code starts to balloon.
This is how you could make it happen:
- Define a script section that uses an “invalid” mime type and place your code there. This will be ignored by the browser, so you won’t get any syntax errors.
- Include an external script that searches for scripts of a certain type, converts them, then evaluates.
If you want to see this idea in action take a look here: http://www.machete.ca/x-javascript.html
I can’t be the first person to have thought of this, but I thought I’d tell it on the mountain just incase.
Thoughts?
After going over the Processing.js stuff again, this is what they’re doing. They still aren’t actually parsing the Processing code, but it yields some very interesting results. http://processingjs.org/ is you’re curious.