Skip to content

Instantly share code, notes, and snippets.

@fabien-d
Last active December 27, 2015 04:29
Show Gist options
  • Save fabien-d/7267255 to your computer and use it in GitHub Desktop.
Save fabien-d/7267255 to your computer and use it in GitHub Desktop.
simplified example of an unobtrusive JS module approach -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module approach</title>
<meta name="description" content="">
</head>
<body>
<div data-module="myModule">
<a href="#">Link</a>
</div>
<script>
// =================================================================
// core.js module logic
var modules = [];
var obj = {
addModule: function ( name, fn ) {
modules[ name ] = fn.call( this );
},
init: function () {
var nodes = document.querySelectorAll( '[ data-module ]' );
Array.prototype.slice.call( nodes ).forEach( function ( node ) {
var moduleType = node.getAttribute( 'data-module' ),
module = modules[ moduleType ];
if ( module && ( typeof module.supported === 'undefined' || module.supported( node ) ) ) {
if ( typeof module.init === 'function' ) {
module.init( node );
}
if ( module.events ) {
module.events.forEach( function ( evt ) {
node.addEventListener( evt, function ( event ) {
module[ 'on' + evt ]( event, node );
} );
} );
}
}
} );
}
};
// =================================================================
// myModule.js add module
obj.addModule( 'myModule', function () {
return {
events: [
'click'
],
/**
* Optional: can be used to feature detect things
*/
// supported( node ) {
// return ( some condition );
// },
onclick: function ( event, node ) {
console.log( 'click happened inside a myModule' );
}
}
} );
// =================================================================
// init.js all the things
obj.init();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment