Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created October 22, 2014 23:40
Show Gist options
  • Save ricardobeat/105ba6541e48eec394b4 to your computer and use it in GitHub Desktop.
Save ricardobeat/105ba6541e48eec394b4 to your computer and use it in GitHub Desktop.
blocks 2
;(function(global){
var library = {}
var instances = {}
function define (name, factory) {
if (library[name]) {
throw new Error('Module '+ name +' already registered.')
}
library[name] = factory
}
function require ( name ) {
if ( !library[ name ] ) {
throw new Error('Module '+ name +' not registered.')
}
return instances[name] || (instances[name] = library[name].call(global))
}
global.define = define
global.require = require
})(this);
define('components', function () {
var jQuery = window.jQuery
var _each = Array.prototype.forEach
var _slice = Array.prototype.slice
var uid = 0
var compo = {}
function init (context) {
var elements = (context || document).querySelectorAll('[data-component]')
_each.call(elements, loadComponent)
}
function create (name, def) {
var Constructor = function (element) {
this.el = element
this.$el = $(element)
this.initialize.apply(this, _slice.call(arguments, 1))
}
Constructor.name = name
$.extend(Constructor.prototype, def)
define('components/' + name, function () {
return Constructor
})
}
function loadComponent (element) {
var name = element.getAttribute('data-component')
var Component = require('components/' + name)
var instance = new Component(element)
jQuery(element).data('component-' + name, instance)
}
function getComponent (element, name) {
return jQuery(element).data('component-' + name)
}
return {
init : init,
get : getComponent,
create : create
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>div { padding: 50px; }</style>
</head>
<body>
<div data-component="paint" data-color="blue">
<div data-component="paint" data-color="red"></div>
</div>
<script src="http://r-ec.bstatic.com/static/js/jquery-1.4.4.min/e185cfe54ae7b27a09cc0bdbe1063f3b6275078b.js"></script>
<script src="blocks.js"></script>
<script src="paint-component.js"></script>
<script>require('components').init()</script>
</body>
</html>
require('components').create('paint', {
initialize: function () {
this.color = this.el.getAttribute('data-color')
this.update()
},
update: function () {
this.el.style.backgroundColor = this.color
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment