Wednesday, July 9, 2008

Cross framework javascript - coding for portability

Imagine that you have written a useful javascript widget using your preferred library (dojo), but at work you must use another framework (jQuery), and a customer needs that you code with Prototype.
Now, you can modify your component by hand, replacing the ajax calls (eg from dojo.xhrGet to $.get), the event handling (from dojo.connect to obj.observe...), the effects... What a boring job!

Or you can write a wrapper who dynamically identifies the js library you are using and maps the ajax calls (and the event handlers, etc...) to the correct form for you.
We can write code like this:

var engine = com.nicolarizzo.utils.runtime.currentEngine;
var showMessage = function(){
window.alert("that's all!");
var startup = function(){
engine.byId("currentEngine").innerHTML = com.nicolarizzo.utils.runtime.engineName;
engine.connect(engine.byId("clickMe"), "onclick", this, showMessage);
without the knowledge of the underlying frameworks!

VoilĂ , here a proof of concept, incomplete and inaccurate as usual, using jQuery :)

The mapping is very simple:

// jQuery mappings
com.nicolarizzo.utils.runtime.currentEngine = {
addOnLoad: function(fnToExecute){
return jQuery(document), fnToExecute);
connect: function(trg, evt, context, method){
if(evt.indexOf("on") == 0){
evt = evt.substring(2);
context = context || trg;
jQuery(trg).bind(evt, function(){});
byId: function(id){
return jQuery("#" + id)[0];

Isn't it nice? ;)

Labels: , , , ,