📜 ⬆️ ⬇️

Template-based html object model

After reading the previous topic (http://habrahabr.ru/blogs/javascript/96588/) in the mind emerged old ideas. The approach is well-known, but either it has disadvantages that I don’t see, or Google and I did not understand each other. In general, I could not find a ready-made solution, so in a couple of hours I sketched my own. But since our paths with the java script have diverged at the moment, it was not possible to try it out in a real project.
Two questions are interesting, what do you see as cons and have you encountered similar solutions for javascript?


Each tag (for example, a div) is presented as a function Htmls.div which
returns HTMLElement on output, and accepts any number of type arguments as input:
1) Object - used to define attributes.
2) String - text
3) HTMLElement - nested tag
4) Array - a list of texts and tags.

Two examples


Example 1

We have
var items = [ "x" , "y" ];


We want to get
< div >
< div id ="some" class ="some-class" >
some div
</ div >
some text
< div > x </ div >
< div > y </ div >
</ div >



')
result contains what we want.

var result;
with (Htmls) {
result = div(
div({ id: "some" , class : "some-class" },
"some div" ),
"some text" ,
items.map( function (i) {
return div(i);
}))
.outerHTML;
}


* This source code was highlighted with Source Code Highlighter .


Example 2 of the above topic

data = {
title: 'C pocket reference' ,
type: 'PDF Document' ,
tag: 'programming' ,
created_at: '5.31.2010'
}
with (Htmls) {
var tagUrl = "tags/" + data.tag;
var result = tr(
td(data.title),
td(data.type),
td(a({href: tagUrl}, data.tag)),
td(data.created_at))
.outerHTML;
}


* This source code was highlighted with Source Code Highlighter .


Plain code
Htmls = ( function () {
function initTag(tag, args) {
for ( var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg.constructor == String) {
tag.innerHTML += arg;
}
else if (arg instanceof HTMLElement) {
tag.appendChild(arg);
}
else if (arg.constructor == Array) {
initTag(tag, arg);
}
else if (arg.constructor == Object) {
for ( var j in arg) {
tag.setAttribute(j, arg[j]);
}
}
}
return tag;
}

function createTag(name, args) {
return initTag( document .createElement(name), args);
}

return {
div: function () {
return createTag( "div" , arguments);
}
//
}
})();


* This source code was highlighted with Source Code Highlighter .

Source: https://habr.com/ru/post/96636/


All Articles