diff --git a/README.md b/README.md index e0659d4..cc9071e 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,21 @@ $('#some-element').render('content', { The second argument to the `render` method is of course the context to use in Handlebars to render the template. +```javascript +// will fetch and render to the DOM element whose id is "content" +$('#content').render('template', { + field1: 'Hello', + field2: 'world!' +}, function () { + $('#content2').render('template2', { + field1: 'Another template rendered' + }); +}); +``` + +You can also use the third parameter to pass a callback function to be executed after successful application of the +handlebars template. This helps. chaining multiple template loads. + Helpers and partials -------------------- diff --git a/src/plugin.js b/src/plugin.js index 5e36706..178e9a5 100644 --- a/src/plugin.js +++ b/src/plugin.js @@ -70,15 +70,29 @@ } }; - $.fn.render = function (templateName, data) { - var url = resolveTemplatePath(templateName); + $.fn.render = function (templateName, data, callback) { + var url = resolveTemplatePath(templateName), + $this = this, + + applyTemplate = function () { // applies html and triggers event + var args = [templateName, data]; + + if ($.isFunction(callback)) { + $.when($this.html(cache[url](data)).trigger('render.handlebars', args)).done(function () { + callback.apply($this, args); + }); + } + else { + $this.html(cache[url](data)).trigger('render.handlebars', args); + } + }; + if (cache.hasOwnProperty(url)) { - this.html(cache[url](data)).trigger('render.handlebars', [templateName, data]); + applyTemplate(); } else { - var $this = this; $.get(url, function (template) { cache[url] = Handlebars.compile(template); - $this.html(cache[url](data)).trigger('render.handlebars', [templateName, data]); + applyTemplate(); }, 'text'); } return this;