Skip to content

Instantly share code, notes, and snippets.

@henriquegogo henriquegogo/component.js
Last active Jan 6, 2017

What would you like to do?
Generic component for rendering data.
function Component(elementId, data, propTemplate) {
var ctx = this;
var container = document.getElementById(elementId);
var template = propTemplate || container.innerHTML; = {};
this.setData = this.render = function(option, doRender) {
if (Array.isArray(option)) = [];
for (var key in option)[key] = option[key];
if (doRender != false) render();
function render() {
if (typeof ctx.beforeRender == 'function') ctx.beforeRender();
var templateRendered = ''+template;
for (var prop in {
var propData =[prop];
if (typeof propData === "object" && !Array.isArray(propData)) {
if (templateRendered != template) templateRendered += template;
for (var i in propData) {
var propDataValue = (typeof propData[i] == 'function') ? propData[i]() : propData[i];
templateRendered = templateRendered.replace(new RegExp('<!--'+i+'-->|{'+i+'}', 'g'), propDataValue);
} else {
var propDataValue = (typeof propData == 'function') ? propData() : propData;
templateRendered = templateRendered.replace(new RegExp('<!--'+prop+'-->|{'+prop+'}', 'g'), propDataValue);
container.innerHTML = templateRendered;
for (var prop in {
var propData =[prop];
if (Array.isArray(propData)) {
var propTemplate = document.getElementById(prop).innerHTML;
new Component(prop, propData, propTemplate);
if (typeof ctx.afterRender == 'function') ctx.afterRender();
<table id="tableData" onclick="watchlistComponent.onclick()">
<th colspan=999><!--title--></th>
<th>Avg price</th>
<th>Mkt Value</th>
<th>% Gain</th>
<tbody id="watchlist">
<td class="text-<!--color-->"><!--gain--></td>
<td class="text-<!--color-->"><!--percent_gain--></td>
<th class="text-<!--total_color-->"><!--total_gain--></th>
<th class="text-<!--total_color-->"><!--total_percent_gain--></th>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.