-
-
Save fijiwebdesign/8b7e2f78747e80f64ced99f2f8b40127 to your computer and use it in GitHub Desktop.
JS templating system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/* | |
* Javascript templating system | |
*/ | |
$(document).ready(function() { | |
function loadTemplate(element, path, callback, done) { | |
$.ajax(path).then(function(html) { | |
element.append(html); | |
if (typeof callback === 'function' ) { | |
callback(); | |
} | |
if (typeof done === 'function' ) { | |
done(element); | |
} | |
}); | |
} | |
function loadComponent() { | |
var el = $(this); | |
var callback = $(el).data('component'); | |
var templateName = $(el).data('template'); | |
var template = 'components/' + templateName + '.html'; | |
loadTemplate($(el), template, window[callback], function(element) { | |
// Initialize functions using data-component attributes inside markup | |
$(element).find('[data-component]').each(loadComponent); | |
}); | |
} | |
// Load components | |
$('[data-component]').each(loadComponent); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment