Skip to content

Instantly share code, notes, and snippets.

@lucasdavila
Created October 8, 2011 04:05
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 lucasdavila/1271842 to your computer and use it in GitHub Desktop.
Save lucasdavila/1271842 to your computer and use it in GitHub Desktop.
Menu JavaScript
function Element(childs, options, tag) {
this.initialize(childs, options, tag);
}
Element.prototype.initialize = function(childs, options, tag) {
this.childs = childs || [];
if (this.childs.constructor != Array)
this.childs = [this.childs];
this.options = options || {};
this.tag = tag;
};
Element.prototype.appendChild = function(child) {
this.childs.push(child);
};
Element.prototype.appendOption = function(name, value) {
this.options[name] = value;
};
Element.prototype.render = function () {
var options = '';
for (var keyIndex in this.options)
options += " " + keyIndex + "="+ "'" + this.options[keyIndex] + "'";
var r = '<' + this.tag + options + '>';
for (var childIndex in this.childs)
{
child = this.childs[childIndex];
if (typeof child != 'object')
r += child;
else
r += child.render();
}
r += '</' + this.tag + '>';
return r;
}
function Link(childs, options) {
this.initialize(childs, options, 'a');
}
Link.prototype = new Element();
function List(childs, options, tag) {
this.initialize(childs, options, tag || 'ul');
}
List.prototype = new Element();
function ListItem(childs, options) {
this.initialize(childs, options,'li');
}
ListItem.prototype = new Element();
//helper para criar link dentro do um li
function ItemLink(name, href, options, linkOptions) {
if (! linkOptions)
linkOptions = {}
if (! linkOptions.href)
linkOptions.href = href
this.initialize(new Link(name, linkOptions), options,'li');
}
ItemLink.prototype = new Element();
//instancias
var links = new List([
new ListItem(['Cadastros', new List([
new ItemLink('Pessoa', '/pessoas'),
new ItemLink('Cliente', '/clientes')
]),
]),
new ItemLink('Sobre', '/sobre', {id : 'tenho_um_id', class : 'e_uma_classe'})
]);
console.log(links.render());
//ou, mais feio (js é sempre feio)
console.log('segunda maneira');
var links = new List();
var linksCadastros = new ListItem(['Cadastros',
new List([
new ItemLink('Pessoa', '/pessoas'),
new ItemLink('Cliente', '/clientes')
]),
]);
links.appendChild(linksCadastros);
links.appendChild(new ItemLink('Sobre', '/sobre', {id : 'tenho_um_id', class : 'e_uma_classe'}));
console.log(links.render());
/* resultado:
<ul>
<li>Cadastros
<ul>
<li><a href='/pessoas'>Pessoa</a></li>
<li><a href='/clientes'>Cliente</a></li>
</ul>
</li>
<li id='tenho_um_id' class='e_uma_classe'><a href='/sobre'>Sobre</a></li>
</ul>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment