Skip to content

Instantly share code, notes, and snippets.

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

Embed
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.data = {};
this.setData = this.render = function(option, doRender) {
if (Array.isArray(option)) this.data = [];
for (var key in option) this.data[key] = option[key];
if (doRender != false) render();
}
this.setData(data);
function render() {
if (typeof ctx.beforeRender == 'function') ctx.beforeRender();
var templateRendered = ''+template;
for (var prop in ctx.data) {
var propData = ctx.data[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 ctx.data) {
var propData = ctx.data[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()">
<thead>
<tr>
<th colspan=999><!--title--></th>
</tr>
</thead>
<tbody>
<tr>
<th>Symbol</th>
<th>Price</th>
<th>Shares</th>
<th>Avg price</th>
<th>Mkt Value</th>
<th>Gain</th>
<th>% Gain</th>
</tr>
</tbody>
<tbody id="watchlist">
<tr>
<td><!--symbol--></td>
<td><!--price--></td>
<td><!--shares--></td>
<td><!--avg_price--></td>
<td><!--mkt_value--></td>
<td class="text-<!--color-->"><!--gain--></td>
<td class="text-<!--color-->"><!--percent_gain--></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th><!--total_mkt_value--></th>
<th class="text-<!--total_color-->"><!--total_gain--></th>
<th class="text-<!--total_color-->"><!--total_percent_gain--></th>
</tr>
</tfoot>
</table>
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.