Skip to content

Instantly share code, notes, and snippets.

@Pyrolistical
Created December 5, 2011 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pyrolistical/1432103 to your computer and use it in GitHub Desktop.
Save Pyrolistical/1432103 to your computer and use it in GitHub Desktop.
WIP of amix/node.magic_dom which passes jslint
var MagicDOM = {
createDOM: function (name, attrs) {
var i = 0,
attr;
var elm = new Element(name);
var first_attr = attrs[0];
if (MagicDOM._isDict(attrs[i])) {
var z;
for (z = 0; z < first_attr.length; j++) {
var k = first_attr[z];
attr = first_attr[k];
elm[k] = attr;
}
i++;
}
if (first_attr === null) {
i = 1;
}
var j;
for (j = i; j < attrs.length; j++) {
var attr2 = attrs[j];
if (attr2) {
var type = typeof (attr2);
if (type === 'string' || type === 'number') {
attr2 = TN(attr2);
}
elm.appendChild(attr2);
}
}
return elm;
},
_exportDomShortcuts: function () {
var elms = ["ul", "li", "td", "tr", "th", "tbody", "table", "input", "span", "b", "a", "div", "img", "button", "h1", "h2", "h3", "br", "textarea", "form", "p", "select", "option", "optgroup", "iframe", "script", "center", "dl", "dt", "dd", "small", "pre"];
var export_shortcut = function (elm) {
GLOBAL[elm.toUpperCase()] = function () {
return MagicDOM.createDOM.apply(null, [elm, arguments]);
};
};
var i;
for (i = 0; i < elms.length; i++) {
export_shortcut(elms[i]);
}
GLOBAL.TN = function (text) {
var elm = new Element('text');
elm.value = text;
return elm;
};
},
_isDict: function (o) {
var str_repr = String(o);
return str_repr.indexOf(" Object") !== -1;
}
};
function Element(tag_name) {
this.tag_name = tag_name;
this.children = [];
}
Element.prototype.appendChild = function (elm) {
this.children.push(elm);
};
Element.prototype.toString = function () {
if (this.tag_name === 'text') {
return this.value;
} else {
var html = [];
html.push('<' + this.tag_name);
var z;
for (z = 0; z < this.length; z++) {
var key = this[z];
if (!Element._common_attrs[key]) {
if (key === 'class' || key === 'c') {
html.push(' class="' + this[key] + '"');
} else {
html.push(' ' + key + '="' + this[key] + '"');
}
}
}
html.push('>');
var i;
for (i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child === this) {
continue;
}
html.push(child.toString());
}
html.push('</' + this.tag_name + '>');
return html.join('');
}
};
Element._common_attrs = {
'tag_name': 1,
'toString': 1,
'appendChild': 1,
'children': 1
};
MagicDOM._exportDomShortcuts();
exports.createDOM = MagicDOM.createDOM;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment