Last active
December 28, 2015 03:09
-
-
Save blessdyb/7432824 to your computer and use it in GitHub Desktop.
Create a Infinite Tree Node with JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Tree Node</title> | |
</head> | |
<body> | |
<script src="javascript/vendor/jquery-1.7.2.min.js"></script> | |
<script src="javascript/vendor/mustache-0.7.2.js"></script> | |
<script src="javascript/vendor/underscore-min.js"></script> | |
<style> | |
.node-list { | |
position: relative; | |
margin-left: 15px; | |
} | |
.node-name { | |
} | |
.child-list { | |
} | |
</style> | |
<script> | |
$(function(){ | |
var treeObj = { | |
name: '1', | |
children: [ | |
{ | |
name: '2-1', | |
children: [ | |
{ | |
name: '2-1-1', | |
children: [ | |
] | |
}, | |
] | |
}, | |
{ | |
name: '2-2', | |
children: [ | |
{ | |
name: '2-2-1', | |
children: [ | |
{ | |
name: '2-2-1-1', | |
children: [ | |
] | |
}, | |
{ | |
name: '2-2-1-2', | |
children: [ | |
] | |
}, | |
] | |
}, | |
] | |
} | |
] | |
}; | |
var tpl = '<div class="node-list"><div class="node-name">{{name}}</div>' + | |
'{{#hasChildren}}<div class="node-list">' + | |
'*children*' + | |
'</div>{{/hasChildren}}</div>'; | |
function printJSONWithMustache(obj) { | |
var html = ''; | |
var partial = ''; | |
if (obj.children.length) { | |
obj.hasChildren = true; | |
for(var i = 0; i < obj.children.length; i++) { | |
partial += arguments.callee.call(this, obj.children[i]); | |
} | |
} | |
html += Mustache.render(tpl, obj); | |
html = html.replace('*children*', partial); | |
return html; | |
} | |
function printJSON(obj) { | |
var html = ''; | |
html += '<div class="node-list">'; | |
html += '<div class="node-name">' + obj.name + '</div>'; | |
if (obj.children.length) { | |
html += '<div class="node-list">'; | |
for(var i = 0; i < obj.children.length; i++) { | |
html += arguments.callee.call(this, obj.children[i]); | |
} | |
html += '</div>'; | |
} | |
html += '</div>'; | |
return html; | |
} | |
function printJSONWithMustacheSelfRecurence(obj) { | |
var tpl = '<div class="node-list"><div class="node-name">{{name}}</div><div class="node-list">{{#children}}{{> tpl }}{{/children}}</div></div>'; | |
return Mustache.render(tpl, obj, {tpl: tpl}); | |
} | |
$('body').append(printJSON(treeObj)); | |
$('body').append(printJSONWithMustache(treeObj)); | |
$('body').append(printJSONWithMustacheSelfRecurence(treeObj)); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment