Re: Simplifying element creation

On 6/10/11 9:51 AM, Jonas Sicking wrote:
> On Tue, Oct 4, 2011 at 1:30 AM, Anne van Kesteren<annevk@opera.com>  wrote:
>> So far we discussed having Element.create() and having new methods on Node
>> that would be more practical than what we have today. Maybe we should
>> combine these in some way? Charles proposed some kind of JSON serialization,
>> but I do not think it makes sense to tie it to JSON.
>>
>> It could be something like this:
>>
>> ELEMENT = [NAME, optional ATTRS, optional EVENT_HANDLERS, TEXT | ELEMENT
>> ...]
>>
>> E.g.<div>Hello<a href="/">World</a></div>  is represented as:
>>
>>   ["div", "Hello ", ["a", {href:"/"}, "World"]]
>>
>> Then the new methods we introduce could accept the above syntax to make it
>> easier to append new elements to the DOM.
>>
>>   ele.append(['div'])
>>
>> would append a<div>  element. If you want to append several elements, you
>> would use
>>
>>   ele.append("Hello ", ["i", "World"])
>>
>> I.e. append() takes "infinite" arguments.
> It sounds to me like we're creating a JSON format for the DOM and
> making element.append accept the JSON format. This doesn't sound great
> to me. It basically sounds like too high level to fit enough use
> cases.

Not to mention that you can already do this with a function consisting 
of at most four DOM calls (including innerHTML) and a bit of string 
processing.

>
> It seems better to have an API for creating a single element (with
> attributes and event handlers), and then let people combine calls to
> that to do their own JSON->DOM conversion.

If setting multiple attributes and multiple event listeners with one DOM 
call is important then you should be able to do this on an already 
created element. If we had such methods, eg setAttrValues() and 
listen(), and if they (and the proposed append() method) all returned 
the invoking node, then Element.create would simply be:

function create(name, attrs, listeners, nodes) {
     return 
document.createElement(name).setAttrValues(attrs).listen(listeners).append(nodes);
}

If it was that simple, would people still be asking for Element.create() ??

> Possibly it would make sense for the function to take an additional
> string-argument is used to create a text node which is inserted as a
> child. But I don't think we should add complexity in the form of
> sometimes interpreting that string as a node-name and sometimes as a
> textnode value.

Received on Thursday, 6 October 2011 11:27:34 UTC