HTML Widget System

by Sam Fereday

HTML

<div id="container">
    <div app-widget="graph-widget" app-model="decisions"></div>
    <div app-widget="graph-widget" app-model="steveyCoots"></div>
    <div app-widget="graph-widget" app-model="decisions"></div>
</div>

CSS

body {
    font: 85%/1.4em arial;
    color: #333;
}
#container {
    padding: 1em 1em 0;
    background: #888;
    overflow: auto;
}
.graph-widget {
    background: #ccc;
    padding: 1em;
    margin-bottom: 1em;
}

JavaScript

// The Model
var DecisionsModel = function(){};
DecisionsModel.prototype = {
    name: "Decisions",
    someData: [10, 102, 2234, 234, 234234]
}

var AnotherModel = function(){};
AnotherModel.prototype = {
    name: "Stevey Coots",
    someMoreData: [10, 99, 22]
}

// The Widget
var GraphWidget = function(name, model){
    this.name = name;
    this.model = model;
};
GraphWidget.prototype = {
    uid: null,
    parentElm: null,
    el: null,
    render: function(container, i){
        var uid = this.name + " " + this.makeId();
        this.uid = uid;
        this.el = document.createElement('div');
        this.el.className = uid;
        this.el.innerHTML = this.model.name + " " + uid + " " + i;
        if(!container) return;
        this.parentElm = container;
        $(container).html(this.el);
    },
    makeId: function() {
        return ("000000" + (Math.random() * Math.pow(36, 6)).toString(36)).slice(-6);
    }
}

// Find matching widget
function getWidget(name) {
    var graph;
    switch(name) {
        case "graph-widget":
            graph = GraphWidget;
        break;
        default:
            throw "Unknown widget type: " + name;
    }
    return graph;
}

// Find matching model
function getModel(name) {
    var model;
    switch(name) {
        case "decisions":
            model = DecisionsModel;
        break;
        case "steveyCoots":
            model = AnotherModel;
        break;
        default:
            throw "Unknown model type: " + name;
    }
    return model;
}

// Put matching widget and model together to then make a new widget instance
function constructWidget(name, Graph, Model) {
    var data = new Model();
    var graph = new Graph(name, data);
    return graph;
}

// Get any app-widget tags and create the widget to go in it
function getPageWidgetsFor(container) {
    var graphid, modelid, newWidget;
    var widgets = [];
    var widgetTags = $(container).find("[app-widget]");
    $.each(widgetTags, function(i, item){
     ...