My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Thursday, July 30, 2009

The Daily Ext JS WTF!

I am getting bored ... the cost per use enterprise ready UI library we all heard about has some intrinsic, internal, illogical logic!

I already wrote how to hack JsonReader to obtain expected behavior.

I have already posted how to solve the TreePanel arrows inconsistency ... what I have never said is that my version of Ext JS is 30% hacked via overrides, extends, or directly in the core and 70% hacked in my application code to make it widely work as expected.

The Layout Problem


I am constantly trying to fix missed rendered components, layout problems, not visualized stuff ... I am hacking the entire layout process in Ext JS 2. Apparently version 3 with about 1000 fixes and enhancements should have solved layout problem but what I think is: how can be possible that probably the only library with a license for commercial purpose has to be that problematic with layout? The answer is that to make things "delayable" layout s not synchronous. I had then to hack with my timeouts automatic selections, forcing for example a grid to have first row selected 'cause if you use the specific method you do not obtain what you expect: a selected row!
Does it make any sense? Down to hack the behavior changing classes manually and run-time ... Cheers!

The Grid Row Inconsistency


Today during a presentation the impossible happened: a click between two rows, probably in the border, probably in that pixel that should not be there, or better, is not logically managed!
The GridPanel, and this time it is the same for both version 2 and 3, has an horrible bug. If you click exactly in the middle of two rows it could select one of them without firing the rowclick event.
How can be possible? It is simple: they decide to manage rows differently between the SelectionModel and the GridLayout so that the selection model could be "activated" accidentally highlighting the row without firing the rowclick/rowmousedown event. Are you kidding me?
Let's explain to a customer that that row was not truly selected ... and after you receive hundreds of insults, let's go in the forum to see if anybody was brave enough to admit that the logic behind the Grid is absolutely a joke.

I had to file a bug for Firefox after I spent half a day to hack the grid to simply make text selection possible and I had to recursively hack the element style parent after parent to force MozUserSelect="text" in order to make that selection possible. I had to hack the grid via an asynchronous event in the selection model, rowselect, finding manually the incriminated div and manually firing the rowclick event when it is not fired because of the "selection model border" ... BLOODY HELL!!!

Sorry For This


I still think Ext JS is one of the best "ready to use" UI libraries but I am truly annoyed by silly logics/stuff like the one described. I am day after day regretting I did not choose the YUI Library which is similar, component speaking, free, and event handling speaking definitively more reliable ... if you guys in Ext need some help from a JS developer give me a shout, I have dunno how many fixes for you, but please, if not, do not rush with releases and make everything as robust as you can.

Best Regards

P.S. to be honest, I would like to have time to develop my UI project, but apparently nobody pays me enough time to do that and everybody wants quick solutions. These are results, I wonder not that skilled web developers what they do when they have a problem, probably they simply wait next release ... how can you call this Enterprise? Ext GWT guys, I am talking with you as well ... bear in mind JavaScript is nor a toy neither a joke, JavaScript is a language and as programming language it requires a proper programmer.

Wednesday, July 29, 2009

PyramiDOM - Spectrum DOM Analyzer

Update PyramiDOM source code and a new bookmark available


During a post into jQuery developer list, I wrote a sort of non-sense reply talking about the DOM as a three dimensional space to analyze and " ... bla bla bla ... " (that was not so interesting, just probably "futuristic" ...)

But why not, why can't we escape from ordinary convention to analyze a document creating a sort of DOM spectrum as is for Audio, Video channels, and other medias?

As quick start test, I have created an alpha version of PyramiDOM, a script hopefully short enough to be clicked, saved, or dragged as a bookmark and able to put a spectrum inside whatever page we are surfing.

The generated spectrum will contain every single nodeType 1 present in the document and will show via tooltip info about that node (nodeName, id if present, className if present). Moreover, it highlights somehow that node temporary changing the background (yellow one). The most wicked effect was in jQuery website itself, since it is dark, and since it is linear enough (you scroll and the spectrum is almost there where you scroll).

On the other hand, the most interesting spectrum was in Gmail, where you can spot a proper pyramid of nested divs. Each nodeName will have the same color, but for practical reasons each time this color will be different (random).

If anybody will like this idea I will post and comment the source code ;-)

Tuesday, July 28, 2009

Some Fun From NekoVM Specs

Few minutes ago I've read about last haxe miracle: translation from an AS2 like ECMAScript 4th programming language, haxe itself, into C++ rather than "just" JavaScript, PHP, and ActionScript 2 or 3, or Neko.

NekoVM is a project I already knew before but since not a single host I know supports it, I have never investigated too much about its features but apparently NekoVM is a damn fast Virtual Machine for Neko code which is basically JavaScript with few differences/limitations. It is still a prototypal based programming language, and we all love it, isn't it, plus some better rule about static types, bytes management, closures, goto statement with portable scope, operator overload for objects, ability to compile C files into ndll, Apache module, MySQL, Zlib, on and on ... truly interesting!

Reading quickly the entire language specs, I tried to figure out if it is possible to reproduce Neko via JavaScript in order to use one language for both server and client: Jaxer style (I do not link Jaxer 'cause AFAIK it seems to be a failed project).

Well, I think without a sandbox it is possible to reproduce 70% of language specs. Via sandbox probably 85%, but 100% is quite utopia due to operator overload not that easy to manage via JavaScript and valueOf in a cross browser way (with firefox it is more simple thanks to "number" string as first argument if the operation is a plus so __add rather than __radd could be partially possible ... never mind).

$apply and $closure from NekoVM


These two functions are both simple and useful in our daily JS tasks. $closure is usually known as delegate or bind, while $apply is some fun we could have in a flexible language as JavaScript is.

function $apply(fn){
// WebReflection from NekoVM
var length = fn.length,
args = []
;
return (function $apply(){
args.push.apply(args, arguments);
return length <= args.length ? fn.apply(this, args) : $apply;
}).apply(this, args.slice.call(arguments, 1));
};

Test case from the source?

var f = function(x,y) { return x + y };

alert(
f(1,2) === $apply(f,1)(2) &&
f(1,2) === $apply(f,1,2) &&
f(1,2) === $apply(f)(1)(2)
); // true

I like the multi bracket style and thanks to its nature it is possible to split a function up to some parameter and inkect different scopes:

var f = function(b, c) {
return this.a + b + c;
};

var o1 = {a:1},
o2 = {a:2},
k = 2, // constant ...
sum = $apply(f)
;

o1.sum = sum(k);
o2.sum = o1.sum.call(o2); // injected
// o2.sum = sum(k); // equivalent


alert(o1.sum(3)); // 1 + 2 + 3 == 6
alert(o2.sum(3)); // 2 + 2 + 3 == 7

I am not sure if "this" should be that malleable, probably a version with static "this" during first call could be better?

function $apply(fn){
// WebReflection V2 from NekoVM
var length = fn.length,
args = [],
self = this === window ? null : this
;
return (function $apply(){
args.push.apply(args, arguments);
return length <= args.length ? fn.apply(self || this, args) : $apply;
}).apply(self, args.slice.call(arguments, 1));
};

In above case if we call $apply() the scope will be malleable, otherwise it will be fixed $apply.call(o2, a).

The other one is less problematic, since it is a common bind.

var $closure = (function(){
// WebReflection from NekoVM
var slice = Array.prototype.slice;
return function $closure(fn, self){
var args = slice.call(arguments, 2);
return function $closure(){
return fn.apply(self, args.concat(slice.call(arguments, 0)));
};
};
})();

The idea is to be able to trap directly the scope in order to make it safe whenever and however it is executed.

var add = function(x,y) { return x + y };
var plus5 = $closure(add, null, 5);
alert(
plus5(2)
); // 7

var add = function(y){return this.x + y};
var plus5 = $closure(add, {x:5});
alert(
plus5(2)
); // 7

Easy? Let's see what else I could create from NekoVM specs 8-)

Monday, July 27, 2009

back in town with a little CSS present

Hi everybody! I am definitively back in London: completely tanned, thanks to Ancona holidays, but right now under the rain (OK, in this second it's sunny here...)

This is a quick "here I am again" but with a simple and little present:

Easy CSS Reset Creator


Sometimes we need to reset CSS to be sure that our document will be clear and hopefully equal for each browser, respecting our rules rather than browsers default.
To better understand what I am talking about, please have a look into this Eric A. and Kathryn S. Meyer page, the basis used to create my simple tool.

What Eric did not think about, is that thanks to Web 2.0 injections and flexibilities, it could be useful to reset a single node and everything contained rather than a full document, specially when we need quick improvements or our cool widget/gadget to add somewhere in the page without an iframe or inherited rules.

So, this is the page able to create the CSS you need with or without a parent rule.

If you need a parent container you can simply use a query string like
http://www.3site.eu/css.reset.php?parent=.myelement

Obviously you can add more complex rules like
?parent=table.test td.last
or, if you need an id, a dollar character rather than a sharp one:
?parent=$myid

where $myid will be converted into #myid

Please note that my host is not that expensive so it cannot handle hundreds f requestes (copy and paste or download the resulted CSS rather than use it directly as link source)

I guess that's it, and see you soon ;)

Thursday, July 16, 2009

[IT] ri-italia.it, parere veloce veloce

Come benvenuto abbiamo una pagina dal leggero peso di 588Kb, per un'immediata impressione di lentezza pachidermica ed un loading time da 1 minuto e 13 secondi su un totale di 72 inutili richieste.

Se togliamo le immagini, le immagini appese in seguito via jQuery e/o plugins, e il filmatone flash che non poteva mancare, praticamente è una pagina bianca: perchè noi italiani non abbiamo niente da dire, basta mostrare la faccia e la firma del nostro presidente per far si che chiunque possa capire al primo sguardo di che pasta è fatta l'italia odierna.

Pratiche stra note per ottimizzare il sito nemmeno una, in compenso una sfilza infinita di javascript per jQuery più non so quanti plugins tutti usati su un file unico per un evento onReady che farebbe piantare i PC più datati non appena la pagina è stata caricata. (per i trolls: c'è il mio nome nei sorgenti di jQuery quindi so di cosa sto parlando)

Stesso discorso per i css: a quanto pare siamo così avanti che YUI Compressor in build sia per l'unico javascript che per l'unico CSS, ad eccezione dei due per IE6 ed IE7, era chiedere troppa tecnologia ... tanto più che la sfilza di css e js è sistematica, qualunque pagina stiamo navigando.

Questo in aggiunta all'ammontare imbarazzante di "immagini ed immaginine", più il filmatone flash, più tutti i commenti nella pagina degni del framework più superficiale incapace di rimuovere commenti assolutamente inutili e per di più con tempi ridicoli, se quelli sono i tempi (0.4 secondi per un unico modulo da quattro immagini in croce ... complimenti per il framework utilizzato) servono a ricordarci quanto la situazione ADSL in Italia sia ridicola con una penetrazione ancora insufficiente.
Ma a noi che stiamo bene non ce ne può fregare di meno!

Con questo Welcome, il tasto in fondo con scritto Accessibilità l'ho evitato in pieno poichè non c'è bisogno di arrivare a cliccarlo per capire che il contenuto della pagina accessibilità avrà probabilmente la dicitura:


Accessibilità
Stiamo cercando di comprendere meglio cosa diavolo significhi.



e niente altro, dato che persino Magic Italy, la rivista, suppongo pensata per il resto del mondo, richiede flash player, senza navigazione tab based, e anch'essa ovviamente pesantissima.

Dato che c'erano dei testi oltre al PDF e le immagini dei PDF da mostrare in modo così advanced, potevano metter i testi nel sito in modo da essere facilmente letti ed indicizzati anche da motori di ricerca stranieri? utopia

Vado su Marche, la mia mata regione, e noto subito che le sotto sezioni non sono indicizzate a modo (briciole inutili) se non nella mappa del sito ... e vabbèh, almeno quella!
Filmatone solito in flash ed un avviso prima di mostrarlo: per vedere questo filmato devi installare il seguente plug-in Adobe Flash player ... vado quasi per clickare quand'ecco che il filmatone appare ... meglio così, ce l'avevo già!

La descrizione non è legata al filmato, comunque grazioso.
Siccome vivo e lavoro qui a Londra mi son detto: proviamo la versione inglishhhhh ... clicko inglishhhh ed ecco che riappare l'avviso di prima, ovviamente sempre in italiano:
per vedere questo filmato devi installare il seguente plug-in Adobe Flash player ... Excuse Me?
Almeno il resto sembra essere in inglese, ma anche dopo questa visita veloce, Accessibilità è ancora una parolona grazie ad errori così banali impensabili con 10 milioni di euro come commissione.

Siccome continuo a vedere in Firebug, il fantastico plugin per il browser Firefox, che il template di testata è praticamente statico mi domando: ma porca miseria già che non hanno usato i giusti headers sopra un unico file per agevolare almeno il caching di tutti quegli scripts tramite un unico file, mi fai vedere che diavolo modificano tutti questi files?

javascript:(function($,r){window.$=function(){r=$.apply(null,arguments);alert(r.length);return r}})($);


Copiando ed incollando questo banalissimo script sulla barra degli indirizzi mentre la pagina sta caricando e dopo che jQuery è stata scaricata (al primo script tag caricato dopo jQuery ne siamo praticamente certi) avrete un alert per ogni chiamata alla libreria e/o plug-in utilizzato.
Ebbene, tutti quegli zero che vi si pianteranno davanti uno dopo l'altro sono l'insieme degli inutili plug-in messi li "per fare mucchio" e per creare un unico file di gestione client qualunque sia la pagina.
In soldoni, non avendo utilizzato pratiche comuni di speed up, e qualunque tool serio ve lo può dimostrare e spiegare, ancora mi chiedo se a creare il sito sia stato un team di webbisti della domenica o se ci sia qualche ingegnere con carenze tecniche a dirigere questo team.

Conclusione


Non riesco a capire se sia meglio o peggio dell'altro ma sicuramente è tecnicamente più semplice (di qui tempistiche più normali).
Meno sezioni, meno sotto sezioni, meno contenuti, credo stesse immagini probabilmente ri-sfruttare, che andrebbe anche bene, ma una serie di pratiche non dico amatoriali ma poco ci manca ... tutto questo non giustifica un investimento di 10 milioni di euro, opinione assolutamente personale.

Personale non è invece il report di Web Page Analyxer:

Download Times*
Connection Rate Download Time
14.4K 940.07 seconds
28.8K 493.13 seconds
33.6K 429.29 seconds
56K 276.05 seconds
ISDN 128K 116.59 seconds
T1 1.44Mbps 52.31 seconds


Analysis and Recommendations



  • TOTAL_HTML - Congratulations ... e ti credo, come ho già detto ci sono zero contenuti da indicizzare

  • TOTAL_OBJECTS - Warning!

  • TOTAL_IMAGES - Warning!

  • TOTAL_CSS - Warning!

  • TOTAL_SIZE - Warning!

  • TOTAL_SCRIPT - Warning!



Questa volta i nomi degli autori/responsabili li abbiamo?

P.S. Bisogna essere obiettivi su un fatto reale: Magi Italy è lo slogan più azzeccato della storia.
Come facciamo sparire i soldi noi, nemmeno David Copperfield ci riesce!

Wednesday, July 15, 2009

The Fastest Date toJSON and fromJSON?

I know yesterday post supposed to be the last 'till the the end of the month but I could not resits. Dustin Diaz twitted

anyone trying to parse our wonky rails dates in JS. do this: var date = Date.parse(str.replace(/( \+)/, ' UTC$1')); seems to fix it.

Again, I could not resist to create a toUTCString based function to create JSON strings and to parse them back. This is the result and apparently is both the fastest implementation I know and cross browser (Chrome, Firefox, Inernet Explorer, Safari).
This is a quick post so if you find some problem please let me know, thanks.

(function(){
// WebReflection Fast Date.prototype.toJSON and Date.fromJSON Suggestion
var rd = /^.{5}(\d{1,2}).(.{3}).(.{4}).(.{2}).(.{2}).(.{2}).+$/,
rs = /^(.{4}).(.{2}).(.{2}).(.{2}).(.{2}).(.{2}).+$/,
d = new Date,
f = /(GMT|UTC)$/.exec(d.toUTCString())[1], // cheers gazheyes
m = {},
i = 0,
s = ""
;
d.setUTCDate(1);
while(i < 12){
d.setUTCMonth(i);
m[s = /^.{5}(\d{1,2}).(.{3})/.exec(d.toUTCString())[2]] = ++i < 10 ? "0" + i : i;
m[m[s]] = s;
};
Date.prototype.toJSON = function(){
var e = rd.exec(this.toUTCString());
return e[3].concat("-", m[e[2]], "-", e[1], "T", e[4], ":", e[5], ":", e[6], "Z");
};
try{Date.fromJSON(d.toJSON());
Date.fromJSON = function(s){
var e = rs.exec(s);
return new Date(Date.parse(e[2].concat(" ", e[3], " ", e[1], " ", e[4], ":", e[5], ":", e[6], " ", f)));
};
}catch(e){
Date.fromJSON = function(s){
var e = rs.exec(s);
return new Date(Date.parse(e[3].concat(" ", m[e[2]], " ", e[1], " ", e[4], ":", e[5], ":", e[6], " ", f)));
};
}
})();

Basically everything is a shortcut and I am using only native methods ... is there anything faster except probably a substr based one?

Tuesday, July 14, 2009

[Webadamus] First Delirium

Introduction


How many times we read news and we think "I knew it was going to happen!"?
How many times we think about a revolutionary project and few days before we are ready to introduce it to the rest of the world somebody, often with more money invested, introduced the same concept but with famous name behind and taking all the glory over that idea?
Which developer interested about Web, reading about ex-imminent Internet Explorer 8, thought "come on, it's Microsoft, we all know they have no interest to create a truly advanced browser, 'cause Internet with more power inside a browser could make an Operating System partially obsolete"?
And who was truly surprised about Google OS announcement?
Webadamus will be a periodic Web Crystal Ball post here in WebReflection. It will talk about visions, thoughts, prototypes, and everything related to the future of the web and the most important thing is that everything will be just my imagination and nothing else. Are you laughing? Are you interested? It's just an experiment, let's see in few months or years, if I was right, are you with me? Let's start then with my first delirium!



Twitter: What's Next


The real potential of this famous service is almost unlimited, except for its 140 characters which, as limit, simply means they can manage more information than every other search engine. Gigabytes speaking, a tweet is meaningless while a web page size could be the equivalent of 100 tweets. And you know what? In a search engine what is important is the chosen title, the content, how much this site is paying to be in pole position, how much this site is spamming links around the net, etc etc ... In twitter, if search a subject selecting meaningful keywords, you will find only people truly interested in that website and for this reason, they re-twitted it. Waist of time? Almost zero, you search by people comments, you do not search by money and advertisement. Popular web sites? THey will be there ... crappy website? They will be unrated. But what is going on behind the tweet fuss?

blacktwit


It could become an integrated service, or it could become simply a third part one, related via API. The blacktwit will contain the classic black list of twitter users. As virus, there are robots or malicious users which only aim is to create fakes account in order to pump up replies, followers, and followed. These users will be able to follow us as well, studying our messages, and in the worst case scenario, spamming/scamming any sort of website. Being twitter the place where url are 80% masked by "url minifier web services", 30% of us will click that link and what's next does not matter, their mission has been completed. Thanks to blacktwit, our favorite twitter application will be clever enough to discard every message automatically or to ask us if we trust that user.

twitcode


I personally posted a couple of "twitcodes", almost complete web programming scripts in less than 140 characters ... but this is not what I mean. twitcode will be a service which aim is to send and recieve instantly quick reviews and votes about a product. #801245632+ will mean that the product in the shop or supermarket with bar code 801245632 has been appreciated while "-" at the end will mean the buyer did not like it. "#801245632- no batteries included" will be a minus plus a comment. #801245632= will return number of users, and how many of them appreciated that product. Example: 10 users with that product, 6 appreciated it, the hash twitcode robot will reply 6/10 plus eventually a random comment, so if we do not like that comment we can tweet again and read the next. At the same time, this service will automatically have a database of interests and opinions in real time, something extremely important for any marketing purpose.

Private Services


As long as our twits are public we cannot use the hash too much. Here is where clever companies will create better robots able to manage private messages.
d twitdeal #insurance Grande Punto 1.3 Split
will be a direct message to user twitdeal that will instantly return the best option for that car while "d twitshop #price Asus 1101HA" will return the best price and the website for that product. It's all about fantasy and nothing else, but a quick service that does not require time neither thousands of pages to visit is a key for a quick future in this "everything in your hands" era.



Internet Explorer 9 Will Be Advanced


Microsoft, the most farsighted company during good old 90s, is loosing market share day after day. Slowly, slightly, but this is simply what is going on or, for sure, what everybody feels about this name. Innovation, does not exists, Silverlight is an Adobe clone with some extra feature already present in Google Chrome with some Chrome Plugin, a la O3D. People excited by hardware acceleration, should simply watch latest WebKit video about Snow Stack. Nothing new, not a single strategy able to bring innovation. A "new" search engine which development is distributed for each country for gosh knows which reason.
A browser which has desktop features like accelerators, and nothing else new enough for its purpose, surfing the Web, except some partially implemented feature a la Object.defineProperty, compatible 1/3 of what Firefox and Safari are able to do since ages with any kind of objects and via __defineProperty__ et similar. Latest news are about Office 2010 Online, something not even scheduled because it will never be innovative enough "thanks to missed Internet Explorer 8 features". If Silverlight will be a requirement, Office 2010 online will be, imho, a partial flop. Google has already done something better, and ages before. For these reasons, and many more, Microsoft at some point will realize that if next browser will not be better than next Operating System their market will fall down as never before. That is why Internet Explorer 9 will the probably the best browser so far, and not just a toy.



Google OS Will Fly High Later


Users are not ready yet ... Google manages big numbers but home users still want more than Web. Maybe because they do not know yet what Web has to offer, considering 50% or more are still using Internet Explorer. Maybe because they want do their business without internet, or maybe because they do not feel secure, thinking that their anti viruses beside probably some cracked software installed is more secure than an Operating System not affected by viruses and spyware at all (this theme will be in another Webadamus post).
Anyway, as somebody already said, minimalist Linux distributions with just Firefox already exist, and it is not only Ubuntu.
We all know that when there is Google name behind whatever market strategy, some how this will reach the goal.
We all know that as is for Netbook, first Google OS devices ( shall we call them Gbooks ? ) cannot cost more than 150 pounds.
How can people otherwise realize that they cannot live without? It will be a winning strategy, but it will take about 2 years before truly relevant results.



Passwords, As We Know, Will Disappears


This is the last delirium from Webadamus, but it is just a logic consequence about passwords. Let's analyze facts before!
More services we have, more our passwords are exposed. If a service lets us choose which password we prefer, most of the time will be the same for every service.
I am not even considering all those websites where the word "security" is meaningless, able to be cracked in a couple of sql injections or via browsers bugs!
How secret is a password? First of all, most common passwords are birthdays or anniversary dates. Sometimes these passwords are just names, swearing words, and 90% of the time these passwords contain only ASCII characters plus some number.
The most secret place for different passwords, or those generated automatically via a super SHA1024 unique hash algorithm, is usually a post it in the monitor. Somebody that feels half an hacker was clever enough to hide his password under the keyboard, still with a post-it. My bank account asked me to choose a password, and a super secret password, so I had to attach another post-it somewhere to digit one pwd first, and the second one after ... brilliant!!! The problem is intrinsic ... if I need money from a cache point, I have to hide numbers I need to digit so mistakes are more frequent and everything is in any case monitored 24/7 by the cash point camera, top right or directly over my head ... brilliant! In the supermarket I have rarely seen somebody remove the pad to digit the card pin number, while everybody is transverse and could potentially check it. It is common sense to do not look somebody doing it, but security is an utopia.
A lot of web users complained about this system of user/password which is absolutely boring and which does not improve security a single bit. This is the reason OpenID exists, but obviously we like choice so these kind of services are numerous ... another flop!
The concept is: please identify yourself to use this service, whatever service it is. In few years, we will all be a number, a product with a barcode, and we will all agree about this new system because everything will be more simple. The way to identify us? It could be a special universal key, card, passport, something we should check every second otherwise we will need to contact the unique number: 10
Telling that our ID is lost, and blocking in real-time every device connected into the central database ... sounds scary, but it is the only solution we have to make things more simple, unless we do not want to live wolverine style in a wood maiden house in the middle of nowhere (sounds like an adventure, isn't it?)


As Summary


This post is not that technical at all, it could be partially obvious and partially hilarious but this will be probably the last until the end of July or first days of August. I am going back in Italy for my sister wedding, friends, food, and hopefully sea under the sun ... so, what a better occasion to be insulted while I am far away from this PC with this USB temporary broadband? Have fun with Webadamus!

Sunday, July 12, 2009

Elsewhere - Sandboxes Have Never Been That Easy

One of the most common problems in Web 2.0 Development, is the amount of libraries we can possibly include into a single project and conflicts these libraries could have.
Some library is truly aggressive. It could change the entire behavior of each other lib present in the page via not-standard or future implementations of some global object prototype, such String, Object itseld, Array, or others.
Since this is a well known problem, some library/framework can try to avoid conflicts in different ways. As example, jQuery has a noConflict method which aim is to make development as painless as possible ... but it is not always that simple. One of Elsewhere purpose is to connect a completely different and external scope into the main window, avoiding any sort of conflict a library with its global properties, functions, or prototypes, could have. First example:

new Elsewhere(
"scripts/libs/jquery.1.3.2.min.js"
).execute(function(ready){
// this scope is elsewhere in a perfectly clean environment.
// In this case jQuery will be manifested as global "$" function.
// To bring jQuery outside, we can use this sandbox parent reference
parent.jQuery = function(search, context){
// to make sure we do not search in an "empty" document,
// the one part of this sandbox, we pass the context
// if not present as parent.document
return $(search, context || parent.document);
};

// we can call the ready callback
ready(parent.jQuery);
},
[ // one or more arguments to pass into Elsewhere function execution
function($){

// let's do something on ready event
// please note there is no var in front of jQuery
// since it has been declared as global
jQuery(function(){
// we could use the argument as well
// since in this case it is exactly
// the same jQuery function
$("body").html("Here I Am");
});

}
]);

Confused? Please read more ;)

Quick Answer: What Is A Sandbox


Every time we open a new window in our browser, the latter one creates a (almost)clean environment to run, if presents, each JavaScript file. The same happens for each tab, which means that if we define a function Z(){} in tab a, this will not be present in tab b. Finally, same things happens inside frames or iframes as well. Each window, framed, tabbed, or not, will have then its own JavaScript environment and in JS world this is called sandbox.

What Is Elsewhere


Elsewhere is a lightweight, less than 1Kb if minified and gzipped, almost fully cross-browser library (so far compatible with each browser I tested) able to create runtime a sandbox including zero, one, or more scripts. The first showed example, creates a sandbox including jQuery library and bringing its power outside the box.
The important thing to understand, is that used function scope will be completely extraneous to the one the function itself has been created ... in few words, that scope will be elsewhere!
Thanks to possibility to send arguments when this external function will be executed, and thanks to parent or top reference, it is possible to play between different scopes avoiding conflicts, creating bridges, loading JSONP, and more!

// JSONP example
new Elsewhere(
"http://mycoolservice.com?fn=parent.callback"
);
// that's it!

About JSONP, via Elsewhere a response could be more than just a callback. It could be an entire different environment with runtime created bridges. Example:

// output produced by a generic REST service
// myservice.server/name/WebReflection

// a function which name is not a problem
function getReferences(){
return userInfo.name + " has " + userInfo.posts + " posts";
};

// a global object which name is not a problem
var userInfo = {
name:"WebReflection",
site:"http://webreflection.blogspot.com/",
posts:12345
};

// a bridge for Elsewhere instance
// every Elsewhere sandbox has a reference to its isntance
// This reference is retrieved via global sandbox window object
// and the property @_Elsewhere
window["@_Elsewhere"].getUserProperty = function(name){
return userInfo[name];
};

// please note you cannot access that property directly
// window.@_Elsewhere will cause an error
window["@_Elsewhere"].getReferences = getReferences;

// ...

// our main page via Elsewhere
var myservice = new Elsewhere("myservice.server/name/WebReflection");
myservice.execute(function(fn){fn()}, [function(){
alert(myservice.getUserProperty("site")); // http://webreflection.blogspot.com/
alert(myservice.getReferences()); // WebReflection has 12345 posts
}]);


Understanding execute Method: How Elsewhere Works


How can be possible that a function defined inside a scope is totally ignorant about surrounding variables or scopes? It is really simple!
Elsewhere is based on Function.prototype.toString de-compilation, creating passed function directly as script inside the sandbox and returning, if status is ready, its value or undefined.
The important thing to understand is that if we create a global scope variable, this will be present next call, whenever we decide to perform it.

var sb = new Elsewhere();
// sb.ready is true, no external scripts loaded
alert(sb.execute(function(){
// generic function
function sum(a, b){
return a + b;
};

// define sum as global in this scope
window.sum = sum;

// test the function
return sum(1, 2);

})); // will be 3


// do other stuff and ...
sb.execute(function(){
return sum(3, 4);
}); // will be 7, sum was already defined

alert(typeof sum); // undefined
// sum exists only Elsewhere

About the ready status flag, it is instantly true if we do not load external script, while it could be true or false, depending on which browser we are using (in some browser an iframe document with external scripts is loaded sync while with Firefox 3.5 an iframe does not block main page content so it is not sync).

// more than a file ...
new Elsewhere([
// order is respected and reliable
"jquery.js",
"jquery.ui.js"
]).execute(function(onjQueryAndUILoaded, initialTime){
// execute is always performed
// after everything has been loaded
onjQueryAndUILoaded(jQuery, new Date - initialTime);
}, [
// we can optionally pass one or more arguments
function($, elaspedTime){
// let's understand how much it took
alert(elaspedTime);
},
new Date
]);


Understanding extend Method: Fast Bridge


Every time we execute a function inside an Elsewhere instance, we are de-compiling and injecting it inside another document. This operation is not that expensive but if we need to perform some task in that scope frequently, we could consider to extend an Elsewhere instance via its own method, creating a sort of fast bridge between two or more than two different worlds.

// empty sandbox
var sb = new Elsewhere()
// extend returns the instance itself
.extend(
{
extendObject:function(){
var toString = Object.prototype.toString;

// note, this Object is not the main one
// but the one from this sandbox (main not affected)
Object.prototype.type = function(){
var s = toString.call(this);
return s.substr(8, s.length - 9);
};

// avoid future modification
window.extendObject = function(){};
},
createObject:function(o){
// create an Elsewhere Object
return new Object(o);
},

// if an extend key is a global variable
// different from undefined
// this will simply be the variable from
// this sandbox
Object:1,

// if the value is not a function
// it will simply be saved as is
cool:true
}
);

// extend Elsewhere Object.prototype
sb.extendObject();

// test it
var o = sb.createObject("test");
alert(o.type()); // String

// o is not instanceof this main page Object
alert(o instanceof Object); // false

// but it could be used as if was
// an Object
alert(o instanceof sb.Object); // true

alert(sb.cool); // true


As Summary


Elsewhere can open hundreds of possibilities without bringing nothing new, except that browsers are starting to implement different threads for each sandbox (tab, or window) and I expect this library will bring an even more simple way to implement web workers. Right now main points are conflicts resolution, when libraries are able to deal from a sandbox, new JSONP interaction ways, multiple native constructor prototype definitions via one or more Elsewhere instances, just a simple way to load external scripts or ... well, whatever else our imagination could create with such tiny, cross-browser, library. Have fun with sandboxes 8).

The script? Via post title or here, in devpro.it.

Friday, July 10, 2009

ECMAScript 5 Full Specs String trim, trimLeft, and trimRight

During last evenings I have updated a little bit my vice-versa project.
Since vice-versa aim is to bring in every browser what is possible to implement and, in most of the cases, already defined as standard (from W3 or MSDN when it is worthy) I decided to get rid of the Ariel Flesler fast trim proposal to introduce my lightweight full specs String.prototype.trim, trimLeft, and trimRight.
For full specs I mean that vice-versa String.prototype.trim replace exactly same characters replaced by native Firefox 3.5 implementation, rather than only characters which code is less than 33 as is for Ariel proposal.

The good part of vice-versa ( to be honest I cannot find bad parts so far ;) ) is that every single file is stand-alone, so if you do not like benefits the entire "lib" could bring, you can always adopt only one of its files, for example the String one, the Array one, or the last full specs ECMAScript 5 Date constructor, compatible with ISO strings, new Date("2009-07-10") and with a complete toISOString method for each created Date instance (of course even if replaced, new Date will produce instances of Date and their constructor will be Date itself).

If you want to give vice-versa minified a try, a little monster which size is about 5Kb gzipped, please do not hesitate to download it.

Have fun with future standards and few MSDN standard coolness for every browser ;)

Frameworks: To Choose Or Not To Choose

Few days ago the BBC announced the release of their framework called Glow.
John Resig commented this event in a "logical and reasonable way" but instantly different developers reacted over his thoughts.
What John says, in few words, is that BBC developers used jQuery before and they were partially happy with it.
Rather than help jQuery community to grow up, opening tickets, adding patches, or forking the library itself improving it adding Safari 1.3 support, a 0% market share browser that in my opinion is used only inside BBC labs and nowhere else, they decided to spend about 2 years to create a library that apparently does not bring anything new, and which is even more supported by some obsolete or deprecated browser, rather than latest one (Chrome 1 or 2, Opera 10, or Firefox 3.5). This post is about what I think after almost 10 years of Web development experience, where I have used both frameworks and I wrote some for internal purpose. Cases are different for each situation, requirements are different as well as different could be time to create or complete a project.



About Library Browsers Support


Dear net surfers, there is nothing to do, if you need internet, if your business is partially based on internet, if you want everything internet has to offer, you must be updated! That's the story, and this is that simple.
There is not a single valid excuse to be stuck in the past, and if some application in your company works only in IE6, first of all you should consider to upgrade that application, it's deprecated, secondly you should consider alternatives at least for new Web services, that in the best case scenario will suggest you to upgrade while in the worst one will simply do NOT work and you, minority, will just miss that train!

As everybody knows technologies quickly evolves and if you walk down the street with a Walkman rather than an iPod like device, you are mentally 80 years old, retired, and you are missing infinity possibilities, starting from more than an album and hours of music.

Internet, the Web, the Web business, and everything around it, is drastically changing day after day.
Reasons are different, starting from an initial and general misunderstanding about same Web standards and related logics, goals, and behaviors, ending with a revolution that thanks to new technologies, programming languages, and companies, where Google is one of the most important leaders, are acting on daily basis.

In few words: are you a net surfer? Do you need internet? You are probably already upgraded, thanks to be patience and to read this post 'till the end.

Are you someone that does NOT know internet, what it has to offer, does not need it for your business, and surfs the Web few minutes per month?
Do not complain then if the rest of the world that needs internet is moving on in the meanwhile, thank you!

Are you a company that understood only recently the power of the web? If you do not upgrade your browser your business will be decades behind others!

Is IE6 there because of "security bla bla bla"? IE6 is one of the most bugged and vulnerable browsers in the history, fire your system administrator and move on with the rest of the world!

All this effort is just to let you understand that modern web libraries are doing their best to be as much compatible as possible.
Unfortunately, some old browser cannot physically solve "nowadays Web problems" because these browsers have been programmed when internet was nothing more than a "advertisement coupon", with flashing images, providing zero services.

Just consider that an iPhone or a G1, mobile devices, integrate a better browser than IE6 or Safari 1.3 ... is it time to move forward? IE8 is there, as Firefox, Chrome, Safari and Opera are. You have choices, and mainly for free, to avoid to collapse with deprecated services and applications.

So, are you spending money for a Jurassic business, internet time speaking? If yes, why are you wasting money with a browser such Safari 1.3, 98% useless for every recent website, or IE6, forced to be somehow compatible but for its own limits obviously deprecated for modern businesses and applications?

As summary, I do not understand why on earth BBC needs to support people that do not use internet. It could make sense to still support IE6, right now below IE8, market share speaking, but unfortunately still there thanks to people ignorance. But a browser that could be compared with Internet Explorer for Mac, abandoned by Microsoft itself years ago, cannot be a good excuse to avoid libraries ... I simply cannot believe this reason and I would like to have real stats about Safari 1.3 usage in their website.



About Choosing Libraries Or Frameworks


There are hundreds of valid choices out there but this case is mainly about the decision to avoid jQuery.
A good library as jQuery is, if I am not wrong the most used one right now and recently adopted in Wikipedia pages as well, has basically these pro:

  • widely cross-browser supported, more market share than Glow or other home made libraries

  • day after day improvements, bug fixes, speed ups, thanks to an active community, a tickets system and again, thanks to its wide adoption from biggest to smallest website, which can only hep to improve jQuery stability and/or features

  • constant cross-browser tests, which aim is to guarantee stability and functionality over any kind of customer, client, administrator, or simply net surfer


These are not jQuery specific features, these are simply the reason developers prefer to use a well known library rather than an home made one.
Less effort, most of what we need is there, and jQuery is truly reach about plug-ins, so what is not there has been probably already implemented. Charts? Timeline stuff? Widgets? Fields helpers? Almost everything, and it simply works thanks to the core library and its stability, jQuery again.
Just to be honest, I do not even use jQuery except when I need it for compatibility or time reasons, so please do not get me wrong, I am not a fanatic, I read Ext JS, dojo, YUI, and other libraries authors or mailing lists as well so this is just an impartial point of view about libraries and nothing else but, there is always a but, I can understand as well the other point of view ...



About Creating Your Own Library


If we understand the reason a library or a framework is a good choice, whatever programming language we are talking about, even if latter one is created via JavaScript, the most problematic programming language ever due to its intrinsic unstable or different nature (not just one virtual machine but lots of different interpreters, few strictly standard behaviors, thousands of browsers implementation bugs or standards misunderstanding, zero compilation, etc etc) there could be an absolutely valid reason to decide to create our own libraries.
First of all, if we do not want to be "monkeys" but developers, the only way we have to deeply learn a programming language and its problems is to use it as much as possible, without stopping a single day to learn more about it.
If a library/framework does magically everything and we are not curious enough to understand how this library is solving or implementing our daily problems or features, we have probably chose the wrong job, unless we are not designers with different goals, where a library is "just what we were looking for" to quickly solve "that problem" which was not Photoshop related.
Sometimes, we could be simply not interested about the language itself, thanks to frameworks able to translate some "serious language" a la Java or C# into the blamed one: JavaScript (and to be honest I can't wait to laugh about some JavaScript related problem not considered by that framework, who you gonna call: Ghost Busters?!)
Another important fact to consider is the time, never enough in this "everybody agile" web era where if at least the business client core functionality and its tests are delegated to someone else, we are half way through our application goals.
But how different are things if we are plenty of time to develop our own library?

  • we are not necessarily reinventing the wheel, if we are skilled enough, and we have studied problems, features, and adopted solutions, we could simply create something new or just perfect for what we need (as example, the dollar function "is prototype stuff", what jQuery did with it was simply different, but I am sure John will agree about this innovation or "just what we need" point)

  • we will have full control over releases and source code, being able to solve problems in a bit and without dependencies over third parts libraries. We all know that even if have skills to quickly change a library core feature, this library next release could probably mess up our internal patch, or vice versa, and sometimes our case is so particular or simply impossible to reproduce outside our business box, that a ticket could not make sense at all. I personally changed some library core function, or overwritten some core method, and simply because of problems and situations impossible to reproduce into the ticket system. The reason is simple: when the application is complex enough, and it is an internal one (admin areas anybody?), we cannot spend a day to create a ticket which emulates somehow our specific problem. Got the point?

  • the final silly point: we are developers, for code sake, and a typical stereotype is that we are all better than everybody else. In few words, if we think it, knowing what others are doing about same thoughts, we are thinking "better than others", and if we are not shy to write a lot of code and test it, because we have time, why on earth we should depend again on third parts libraries?





As Summary


There is not an absolute point about these kind of choices, except one: flexibility. I do appreciate the fact BBC team at least tried jQuery library before they chose to create their own one. The point about death browsers is an excuse, IMHO, they should have been more decided about their points because if that was the reason, I do not get it at all and people talking about public money would be absolutely right. On the other hand, latest points about proprietary libraries advantages could make BBC site less problemtic, for their supported browsers, considering they know what they are doing, they had even too much time to develop 300Kb of core library comment included ( I wrote 3 times of code in one month over another library and nothing was redundant ... ), and they are (ta da ta da!!!) BBC, good to see their source code (lovely comments, not everything lovely in the code though but this is another story)

This post is just my humble opinion about a subject extremely common in this sector and interesting as well.
I am just a developer with passion for code, curiosity about ASM, C knowledge, a "JavaScript Ninja" currently technical editor of an imminent related book, with PHP Zend Engineer certifications, few Java related experiences, and daily C# exposure. In few words, I have collaborated with different companies and created internal libraries or used third parts libraries. Please consider my experience so far before you'll blame me for this post, thanks :D

P.S. I promise, I'll add every related link asap, right now my temporary Internet connection is running out of bytes!!!

Sunday, July 05, 2009

YUI Compressor Meets The Batch Scripting

Mainly to work, also to investigate some good old DOS feature, I created a batch file able to make YUI Compressor more portable and easy for every Windows based client/server developer.
I wrote the story, and I described each file, plus I added a workable Zip with everything you need to understand what I have created and use it, starting with a double click into a projects/vice-versa.bat file which aim is to create from a list of files a unique YUI Compressed one.
Here is the link, the rest is up to you (comments, questions, suggestions, etc)

Saturday, July 04, 2009

UK Bing Roundtable - Just My Opinion

It is probably too late and I did not check other guys blogs, but I would like to bring here my impressions about this Bing event I have been invited few days ago.

How Did It Start


Hi Andrea,
I'm writing on behalf of Microsoft to invite you to a discussion about Bing, the new search engine that recently launched in beta in the UK.

...

Colin Mercer, a member of Microsoft Life Without Walls initiative group, is a truly nice guy. Spontaneous, friendly, exactly that kind of guy that could let a group of foreigners feel comfortable since first meet up minutes. Being glad to have been invited without asking, and without being a Microsoft fun as well, of course I was there: to understand what this initiative was about and why they called me, raising my doubts from this high geek technical blog.

Bing Round Table, The Good Part


To be honest, I am not going to be that nice about this event, but I have to admit that seeing Microsoft trying to be closer than before with people that make Web live, any topic blogger in this case, was a nice surprise. The organization, the choose place, and the catering was excellent, even if there were only about 10 guests and there was no time to eat and drink. It is a good start point from a company famous to be closed for its selling purpose only. Good Stuff, please keep doing it, it can only brings benefits from different points of view.


Special Moronic Guests, That Is What We Are


The presentation started with a lovely woman and a sort of jingle: "Bing"! OK, that was to make us comfortable, that was to have a quick laugh, that was to break the ice, that was ... only the begin!
The entire presentation showed us stats, those stats were retrieved from God Knows which tool bar present only in Internet Explorer, and those stats, even if from IE world, put Microsoft search engines in third position, I can't imagine what could come from Mozilla or Google, if they present stats based on their own products ... I guess Bing would not even exists ...
Since those stats were not that pro-bing, they stopped into a slide with classical promises a la "it's simple, it's friendly, it's new, it's brand, it's something you should use, it makes your life better" ... no comment.
Fortunately, some guy started instantly to ask what was new, what was interesting, what was the missing piece that other well known search engines do not have ... and every question had behind a though like: why are we here and what are you showing us? We are not dummies and we know what we want, what other offer, and what we are looking for.
Were we interested about TV ad like presentation? NO
Were we interested about promises other search engines maintain since ages? NO
Were we interested about U.S.A. verion, being in London, where Bing is still beta and smells like Live from miles without bringing a single new feature and positioning bing itself in the second place when you search for bing in the uk version? NO
So what were they showing us? Did they think we do not know what is a search engine? Probably

Missed Expectations


At least that what I think,everybody was looking for that genius thing that nobody else have ... it did not happen! Apparently, the most innovative thing is the live video preview for video results ... OK, I want to be honest, I think everybody over 18 has seen some xxx search engine and everybody knows that a quick preview in a video link is not a Bing idea ... isn't it?
The second most important innovation is a vertical focused lateral bar, something that simply remove spaces fr mobile devices, something useful because with that kind of layout and images behind white links people could even not notice top links so here they are with an innovative lateral menu ... is this wow?

Bing UK, I Want Developers Name!


First of all, for a company that sell enterprise software a la Visual Studio Team System, I wonder how it can be possible that whatever country version is different from every other ... merge projects and use one big development team? Naaaaaaaaa, they prefer to delegate search engine development in each country ... what a waist of money! The UK version is a new graphical version of the Live.co.uk search engine, same weird results (Bing itself in second position after a link called News about Bing ...), not a single lateral bar, nothing useful in the home page ... and about this, 110Kb of home page because of course if a user needs to search something he has to wait the castle, the building, the big sized image in home page. Moreover, with 13 inline JavaScript files, when you chose a different search type switching from Web to Image, the entre page is reloaded and the only difference is the form action, using /images/ rather than the main path ... I mean: Are You Serious?
Design wise, as I said in some other post I am partially color blind. I perfectly recognize red and green, but slight gradients make my life truly difficult.
Google, in its simplicity, studied a lot color contrasts to make everything clear, now try to read the disclaimer, or links bottom right ... oh really? You did not even know there were links there? I am not a designer, but you do not need a PHD to understand that bright text over a bit brighter background does not make sense ... now put white text over images loads of details ... and now tell me how long you spent to read that text, and how much all these problems do not exists in both Yahoo and Google. Is it all about design? Does it make sense to create a 100Kb home page just to add noise and confusion? Did they truly need 13 inline JavaScript for a page that has no functionality rather than a field? Where is the simplicity they are talking about?
Google, 25Kb, you write, you press enter, that's it, that's why they are the number one search engine ... no confusion, not a single waist of time or bandwidth, optimized for mobile devices and even if Microsoft has more than one HTC device, they do not care ... try to surf Bing with iPhone or Android ... are we still in 2000 or in the netbook/small screen devices era? A splash in the past, and still nothing new!

Bing U.S.A. You Click Rather Than Scroll!


Again, I did not get this "feature", the vertical oriented menu on the left suppose to make everything simple because in Gogle you have to scroll ... What?
The scrolling operation with a mouse is extremely natural and it can be performed everywhere in the page while it is still natural with mobile devices where with a finger or a dedicated button you just ... scroll! The search, point, and click is a boring, slow, tedious, operation, even more difficult with mobile devices and whatever "finger-pad" panel we all have in our mobile devices. In few words, in UK Bing presentation they showed us how simple is to find Washington map ... you search for Washington, the engine is so clever to understand that you are looking for a city ( again, moronic stuff, we all know that this is the abc for a top ten search engine ) and if you click Map in the left side menu, you will find the map. In Google, you have to scroll ( weird, I always found maps in the top of the page ) to find information, so they organized everything, with a response page which average is again about 70Kb VS 30 to 35 for Google, where in the latter one you can find everything you need in one page, quick, simple, that is simple!
I do not want to comment the fact they proposed U.S.A. related searches, and non UK images in the home page for the UK Bing version ...

There Will Be Time For Technical Question?


After any sort of question and hundreds of good points about missed interesting news for this new Microsoft search engine, I simply called time to ask technical question. THey said yes but thre was no time, and you know what? I got time blowing out loudly and quickly my points producing non-sense sentences cause I lost number of things to ask or say ... but one thing I will never forget: I asked about 13 inline scripts and the reason if in the UK version I click images I have to reload the page just to change a form target ... the answer was: I do not know what you are talking about ... OK, probably misunderstanding, probably not DB related, but at the end of the day, the only though in my mind was this one: Why on earth they called me? Did they think I was a web troll? Did they think I was a teenager with a lot of time to waist behind the PC? Did they ever consider me as a 10 years experienced web developer with deep JavaScript knowledge, server side certifications, and studies that not a single young Phd person have unless he/she has not my same passion?
Disappointed, partially humiliated, and still load of doubts about how the presentation supposed to be and the reason they called us.

Is Everything That Bad?

One thing I truly appreciated, which does not come from this meeting, is the Bing API, in my opinion well done and flexible enough to let us create interesting applications or web gadgets. If you'll stay tuned, I am planning to create a bookmarkable script that will make searches nice, simple, and friendly, exactly how Bing should, in Microsoft mind, be.

Finally, this post is only my impression, my opinions, and nothing else. I may have misunderstood a lot of words/questions, specially after a couple of fresh beers, but I still wonder why I was there ... and if I would like to be there again. Let's see how things will be.

Post Scriptum

All my opinions come from 30 minutes analysis in place, during the meeting, I've never had time these days to investigate the search engine itself so I may have missed something ... again, take carefully what I said about Bing, thanks.

ECMAScript ISO Date For Every Browser

One most than welcome new entry of ECMAScript 5 is the Date.prototype.toISOString function and ability for Date constructor to accept an ISO String and to generate a Date instance.
This feature will make JSON Date instances import/export extremely fast and simple, but why should we wait ES5 release when we can have both features now?

Full Specs ISO 8601 Parser Plus Unobtrusive toISOString Method


We all do not like that much to extend native JavaScript constructors, so here I am with a proposal that will not touch the Date prototype:

if(!Date.ISO)(function(){"use strict";
/** ES5 ISO Date Parser Plus toISOString Method
* @author Andrea Giammarchi
* @blog WebReflection
* @version 2009-07-04T11:36:25.123Z
* @compatibility Chrome, Firefox, IE 5+, Opera, Safari, WebKit, Others
*/
function ISO(s){
var m = /^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/.exec(s);
if(m === null)
throw new Error("Invalid ISO String");
var d = new Date;
d.setUTCFullYear(+m[1]);
d.setUTCMonth(m[3] ? (m[3] >> 0) - 1 : 0);
d.setUTCDate(m[5] >> 0);
d.setUTCHours(m[7] >> 0);
d.setUTCMinutes(m[8] >> 0);
d.setUTCSeconds(m[10] >> 0);
d.setUTCMilliseconds(m[12] >> 0);
if(m[13] && m[13] !== "Z"){
var h = m[16] >> 0,
i = m[17] >> 0,
s = m[15] === "+"
;
d.setUTCHours((m[7] >> 0) + s ? -h : h);
d.setUTCMinutes((m[8] >> 0) + s ? -i : i);
};
return toISOString(d);
};
var toISOString = Date.prototype.toISOString ?
function(d){return d}:
(function(){
function t(i){return i<10?"0"+i:i};
function h(i){return i.length<2?"00"+i:i.length<3?"0"+i:3<i.length?Math.round(i/Math.pow(10,i.length-3)):i};
function toISOString(){
return "".concat(
this.getUTCFullYear(), "-",
t(this.getUTCMonth() + 1), "-",
t(this.getUTCDate()), "T",
t(this.getUTCHours()), ":",
t(this.getUTCMinutes()), ":",
t(this.getUTCSeconds()), ".",
h("" + this.getUTCMilliseconds()), "Z"
);
};
return function(d){
d.toISOString = toISOString;
return d;
}
})()
;
Date.ISO = ISO;
})();

The public static ISO Date method accepts a valid ISO 8601 String compatible with W3 Draft:

Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

where:

YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)

The only limit is about milliseconds and JavaScript Date itself, the latest parameter will be rounded if there are more than 3 digits (JS precision is up to a millisecond, no microsecond yet).
The toISOString method is created for every browser that does not support this prototype yet but it is simply assigned and compiled once to avoid Date prototype problems and to optimize memory and performances.
I interpreted ISO specs as Zulu default:

var normalDate = new Date(2009, 06, 04);
var ISODate = Date.ISO("2009-07-04");

normalDate.toISOString = ISODate.toISOString;

alert([ // being in UK ...

// 2009-07-03T23:00:00.000Z
normalDate.toISOString(),

// 2009-07-04T00:00:00.000Z
ISODate.toISOString()
].join("\n"));

Since solar time is +01 hour, if I create a Date with midnight time, the respective Zulu one (UTC) will be the day before at 23:00:00 while since ISO consider an unspecified Time Zone the Zulu one, +00:00, the created Date will be exactly the specified one but obviously if we try to get ISODate.getHours() it will be 01 and not 00, accordingly with my local settings.

This is a little function/proposal that has zero dependencies, is widely compatible, and could be a standard or a must for every library/framework. Waiting for your thoughts, have a nice we 8)