Skip to content

Instantly share code, notes, and snippets.

@WesSouza
Created October 22, 2014 22:13
Show Gist options
  • Save WesSouza/1bd1312564a8c155a3e3 to your computer and use it in GitHub Desktop.
Save WesSouza/1bd1312564a8c155a3e3 to your computer and use it in GitHub Desktop.
I like LEGO and JavaScript.
( function ( self ) {
var library = {};
var GlobalDomain = {
instances: {},
getInstance: function ( name ) {
var instance = this.instances[ name ] || ( typeof library[ name ] == 'function' ? library[ name ]() : library[ name ] );
this.instances[ name ] = instance;
return instance;
}
}
function register ( name, value ) {
if ( library[ name ] ) {
throw Error( 'Block '+ name +' already registered.' );
}
library[ name ] = value;
}
function use ( name, domain ) {
if ( !library[ name ] ) {
throw Error( 'Block '+ name +' not registered.' );
}
domain = domain || GlobalDomain;
return domain.getInstance( name );
}
self.use = use;
self.register = register;
self.register.library = library;
} )( self );
register( 'core/pieces', function ( ) {
var pieces = {};
function PiecesDomainForElement ( element ) {
return {
getInstance: function ( name ) {
var instance = element[ 'block-instance-of-'+ name ] || ( typeof register.library[ name ] == 'function' ? register.library[ name ]( element ) : register.library[ name ] );
element[ 'block-instance-of-'+ name ] = instance;
return instance;
}
};
}
pieces.init = function ( ) {
pieces.load( document );
}
pieces.load = function ( element ) {
if ( element.dataset && ( element.dataset.piece || element.dataset.pieces ) ) {
pieces.loadForElement( element );
}
Array.prototype.forEach.call( element.querySelectorAll( '[data-piece], [data-pieces]' ), pieces.loadForElement );
}
pieces.loadForElement = function ( element ) {
var blocks = [];
element.dataset.piece && blocks.push( element.dataset.piece );
element.dataset.pieces && blocks.concat( element.dataset.pieces.split( /\s+/g ) );
blocks.forEach( function ( block ) {
use( block, PiecesDomainForElement( element ) );
} );
}
return pieces;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment