Re: Namespace-aware APIs do not need to suck

On Thu, 05 Nov 2009 09:40:48 -0500, Julian Reschke <julian.reschke@gmx.de>  
wrote:

> Maciej wrote:
>> So you could imagine code like this:
>>
>> var el1 = document.createElementNS2("{http://www.w3.org/1999/
>> xhtml/}span");
>> var el2 =  
>> document.getElementsByTagNameNS2("{http://www.w3.org/1999/xhtml/
>> }div")[0];
>> el2.appendChild(el1);
>
> Yes. As a matter of fact, this *could* be just createElement, as the  
> curly braces allow to detect the new format of the argument reliably.

I tried the following with Opera:

(function() {
     var oldCreateElement = Document.prototype.createElement;
     Document.prototype.createElement = function() {
         var args = arguments;
         if (args.length !== 1 && args.length !== 2)
             throw new Error("WRONG_ARGUMENTS_ERR");
         if (args.length === 2)
             return this.createElementNS(args[0], args[1]);
         var pattern = /^\{(.+)\}(.+)$/g;
         var ref = this;
         var el = null;
         args[0].replace(pattern, function(match, ns, name) {
             el = ref.createElementNS(ns, name);
         });
         return el !== null ? el : oldCreateElement.call(this, args[0]);
     };
})();
var x = document.createElement("{http://www.w3.org/1999/xhtml}div");
var y = document.createElement("http://www.w3.org/1999/xhtml", "div");
var z = document.createElement("div");
alert(x);
alert(y);
alert(z);

Using the first way seems pretty cool by me fwiw.

-- 
Michael

Received on Thursday, 5 November 2009 16:49:01 UTC