Info |
---|
This approach is not intended for use with Drupal theme development. Please use drupal behaviors instead to make sure code is run after AJAX requests. |
We currently use the following pattern on many pages, specially for reusable code:
...
Use a module pattern to allow reusable code: https://github.com/umdjs/umd
jQuery Module pattern
Code Block | ||
---|---|---|
| ||
(function(moduleName,$,window,undefined){ … }( window.moduleName = window.moduleName || {}, jQuery, window, undefined )); |
...
Code Block | ||
---|---|---|
| ||
(function(moduleName,$,window,undefined) { kalaStatic.About = function() { this.doSomething(); } /* * Assigning p to the Modules prototype just makes for less * typing. It results in smaller files and, so long as we * keep to one module per file, there should be no problem. */ var p = kalaStatic.About.prototype; p.contructor = kalaStatic.About; // explicitly assing the kalaStatic.About function, as the kalaStatic.About.prototype's constructor p.doSomething = function(){ console.log('doing that thing'); } p.doAnotherThing = function(){ console.log('doing something else'); } /* * We're putting our JS at the bottom of the HTML these days * so $(document).ready isn't strictly necessary, but maybe * best practice. */ $(document).ready(function() { /* * For js that we only want to instantiate on certain pages, * we make sure the body tag has the corresponding class name * This is a kalastatic html.html convention: * <body class="{% if page_slug %}{{page_slug}}{% else %}{{title|slug}}{% endif %}"> * In this case we're assuming the src/about.md has page_slug * defined in the frontmatter as 'page-about'. */ if( $("body").hasClass('page-about') ){ kalaStatic.about = new kalaStatic.About(); kalastatic.about.doAnotherThing(); } }); }( window.kalaStatic = window.kalaStatic || {}, jQuery, window, undefined )); |
...