Skip to content

Instantly share code, notes, and snippets.

@jmas
Last active August 29, 2015 14:23
Show Gist options
  • Save jmas/6d6574ac413855911716 to your computer and use it in GitHub Desktop.
Save jmas/6d6574ac413855911716 to your computer and use it in GitHub Desktop.
Very simple javascript list class
var DataList = function(el, data, itemTpl, populateItemDataFn) {
if (! (el instanceof Node)) {
throw new Error('el should be an Node.');
}
if (! (data instanceof Array)) {
throw new Error('data should be an Array.');
}
if (typeof itemTpl !== 'string') {
throw new Error('itemTpl should be an String.');
}
if (typeof populateItemDataFn !== 'undefined' && ! (populateItemDataFn instanceof Function)) {
throw new Error('populateItemDataFn should be an Function.');
}
this.el = el;
this.data = data;
this.itemTpl = itemTpl;
this.populateItemDataFn = populateItemDataFn;
this.render();
};
DataList.prototype = {
el: null,
itemTpl: '',
data: [],
populateItemDataFn: null,
render: function() {
if (! this.el) {
return;
}
this.el.innerHTML = '';
for (var i=0,ln=this.data.length; i<ln; i++) {
this.el.appendChild(this.makeItemEl(this.data[i]));
}
},
update: function(data) {
if (! (data instanceof Array)) {
throw new Error('data should be an Array.');
}
this.data = data;
this.render();
},
makeItemEl: function(itemData) {
var itemEl = document.createElement('DIV');
itemEl.innerHTML = this.itemTpl;
if (this.populateItemDataFn) {
this.populateItemDataFn(itemEl, itemData);
}
return itemEl;
}
};
// How to use
window.notifyList = new DataList(
document.getElementById('notify'),
[],
document.getElementById('notify-item-tpl').innerHTML,
function(itemEl, itemData) {
var containerEl = itemEl.querySelector('[data-container]');
var userEl = itemEl.querySelector('[data-user]');
var userImageEl = itemEl.querySelector('[data-user-image]');
var userNameEl = itemEl.querySelector('[data-user-name]');
var textEl = itemEl.querySelector('[data-text]');
var actionEl = itemEl.querySelector('[data-action]');
containerEl.classList.add('notify-item-new');
userNameEl.innerHTML = itemData.name;
textEl.innerHTML = 'Hello, world';
actionEl.innerHTML = '<a class="btn btn-primary" href="#">Follow</a>';
}
);
window.notifyList.update([
{ name: 'Hello' },
{ name: 'Bro' }
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment