A simple bootstrap for loading and binding DOM elements to JavaScript modules in an understandable way. A simple glue between the HTML and scripts that act upon it. For more information check out Introducing GroundworkJS.
<!-- webpage.html -->
<div data-gw-component="widget/slider">
<ul>
<li>…</li>
<li>…</li>
<li>…</li>
</ul>
</div>
// js/component/widget/slider.js
define(function() {
return {
init: function(element) { … },
next: function() { … },
prev: function() { … },
teardown: function() { … }
};
});
GroundworkJS utilises AMD compatible modules which are well suited to in-browser development and as an aid to creating scalable code.
A JavaScript module loader such as RequireJS or curl.js.
-
Configure the module loader to include a
component
path// RequireJS require.config({ baseUrl: "/assets", paths: { component: "js/component" } }); // curl.js curl.config({ apiName: "require", baseUrl: "/assets", paths: { component: "js/component" } });
-
Bootstrap the application
<!-- RequireJS --> <script src="vendor/require.js" data-main="js/bootstrap"></script> <!-- curl.js --> <script src="vendor/curl.js" data-curl-run="js/bootstrap.js"></script>
// js/bootstrap.js require(["groundwork"], function(groundwork) { groundwork.startup(); });
Initialises all components within scope.
Teardown all component instances within scope.
Teardown then re-initialise all components. Also cleans up component instances for elements no longer on the page.
Returns the ìnstance of componentName on element.
GroundworkJS is designed to be resilient and will work in any browser with support for querySelector
and Object.create
. IE is therefore supported down to version 8 providing an appropriate shim for the latter is provided.
// js/bootstrap.js
require(["groundwork"], function(groundwork) {
// Cut the mustard
// <http://responsivenews.co.uk/post/18948466399/cutting-the-mustard>
if (! window.querySelector) {
return;
}
// Object.create() shim
// <http://javascript.crockford.com/prototypal.html>
if (typeof Object.create !== "function") {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
groundwork.startup();
});