Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added render callback argument #15

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <template.handlebars> 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
--------------------

Expand Down
17 changes: 12 additions & 5 deletions src/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,22 @@
}
};

$.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];
$this.html(cache[url](data)).trigger('render.handlebars', args);
$.isFunction(callback) && callback.apply($this, 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;
Expand Down