JSFiddle - React, Tailwind, and code Playground
Tree - with ajax fetch of data
by Ben Clayton
HTML
<div id="tree">
</div>
<script id="node-template" type="text/x-handlebars-template">
{{#each .}}
<div class="node" id="node-{{id}}">
<div class="icon-text">
<div class="icon {{iconCls}}"></div>
<div class="text">{{text}}</div>
</div>
<div class="children-wrapper">
</div>
</div>
{{/each}}
</script>
CSS
.folder {
background-image: url(//flowcms.infxsolutions.com/script/Ext_V3.4/images/default/tree/folder.gif);
background-size: contian;
}
.folder.open {
background-image: url(//flowcms.infxsolutions.com/script/Ext_V3.4/images/default/tree/folder-open.gif);
}
.product {
background-image: url(//flowcms.infxsolutions.com/script/Ext_V3.4/images/default/tree/leaf.gif);
}
.icon {
display: inline-block;
position: relative;
top: 2px;
width: 16px;
height: 16px;
cursor: pointer;
}
.text {
margin-left: 5px;
display: inline-block;
}
.children-wrapper {
margin-left: 26px;
}
JavaScript
// create the _infx namespace if it doesn't exist already
_infx = (typeof(_infx) === 'undefined') ? {} : _infx;
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// product tree
_infx.tree = {
// init this functionality
init: function() {
var _self = this;
_self.setup_handlebars();
},
// checks to see if we have handlebars loaded already, if not we load the script wait
// for it to load, then trigger the rest of the initialisation process
setup_handlebars: function() {
var _self = this;
// do we have a Handlebars object loaded, if not we must fetch it here
if (typeof Handlebars === 'undefined') {
$.getScript("//flowcms.infxsolutions.com/script/handlebars.js/3.0.3/handlebars.min.js", function() {
// register handlebars helpers
_self.register_handlebars_helpers();
// render Node 0 which needs no data from server
_self.first_node();
});
} else {
// register handlebars helpers
_self.register_handlebars_helpers();
// check we have the right version, TBC - is there an upper limit?
if (parseFloat(Handlebars.VERSION) >= 3.0) {
_self.first_node();
} else {
console.error('unable to initialise, please ensure the correct version of Handlebars is loaded we require at least v3.0');
};
};
},
// register_handlebars_helpers
register_handlebars_helpers: function() {
var _self = this;
Handlebars.registerHelper("equal_to", function(a, b) {
return (a === b) ? true : false;
});
},
// render first node of tree
first_node: function() {
var _self = this;
var context = [{
id: 0,
pid: 0,
text: "[Products]",
iconCls: "folder"
}];
_self.compiler('#node-template', '#tree', context);
_self.attach_handlers('#node-0');
},
// fetch data and render other nodes of tree
fetch_children: function(pid) {
console.log("fetch...