- From: Sean Hogan <shogun70@westnet.com.au>
- Date: Mon, 03 Oct 2011 22:32:40 +1100
- To: Charles Pritchard <chuck@jumis.com>
- CC: Dominic Cooney <dominicc@chromium.org>, www-dom@w3.org
On 2/10/11 11:00 PM, Sean Hogan wrote:
> Hi Charles,
>
> I see some specific problems with both the Element.create and
> JSON.toNode proposals, but in general I think that blessing one JSON
> representation of the DOM over all others is a bad idea.
>
> Also, it is fairly trivial to roll your own solution (or three) so I
> imagine this feature won't ever be a high priority item.
>
> Here's a (non-robust) solution off the top of my head. I'm sure you
> have an alternative approach that works better for you. This merely
> highlights that this sort of syntax sugar shouldn't be in the DOM core.
>
Oops, this is probably not a great example because it's pretty much the
same as the Element.create() proposal (plus a Fragment.create function).
But it does illustrate how trivial it is. Plus, because it isn't a
native function it would be simple to add in other options, like setting
properties instead of attributes, adding event listeners, etc. Obviously
you wouldn't get that flexibility with a standard Element.create(), and
if you wanted those options Element.create() wouldn't make it any simpler.
> var $ = { // WARN this API is for demo purposes only
> F: function(nodes) { // create a document Fragment and append nodes
> (which is an array)
> var frag = document.createDocumentFragment();
> nodes.forEach(function(node) {
> if (typeof node === "string") node =
> document.createTextNode(node);
> frag.appendChild(node);
> });
> return frag;
> },
> E: function(tagName, attrs, nodes) { // create an Element with attrs
> and child nodes (if present)
> var el = document.createElement(tagName);
> if (attrs) for (var name in attrs) el.setAttribute(name,
> attrs[name]);
> if (nodes) el.appendChild(this.F(nodes));
> return el;
> }
> }
>
> An example of usage:
>
> To create '<div class="greeting">Hello <b
> class="target">World</b>!</div> ' and retain references to the <div>
> and <b> elements:
>
> var greeting, target, frag = $.F([
> greeting = $.E("div", {"class": "greeting"}, [
> "Hello ",
> target = $.E("b", {"class": "target"}, [
> "World"
> ]),
> "!"
> ])
> ]);
> greeting.onclick = function() { alert("Hi"); }
> target.onclick = function() { alert("I am the World"); }
>
Received on Monday, 3 October 2011 11:33:08 UTC