Skip to content

Commit

Permalink
wrap afterRender callback, so it is not called until template is ready
Browse files Browse the repository at this point in the history
  • Loading branch information
rniemeyer committed Jan 1, 2014
1 parent 6b1c18c commit 965e735
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/amdTemplateEngine.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
(function(ko, require) {
//get a new native template engine to start with
var engine = new ko.nativeTemplateEngine(),
existingRenderTemplate = engine.renderTemplate,
sources = {};

engine.defaultPath = "templates";
Expand All @@ -13,12 +14,17 @@
this.key = key;
this.template = ko.observable(" "); //content has to be non-falsey to start with
this.requested = false;
this.retrieved = false;
};

ko.templateSources.requireTemplate.prototype.text = function(value) {
//when the template is retrieved, check if we need to load it
if (!this.requested && this.key) {
require([engine.defaultRequireTextPluginName + "!" + addTrailingSlash(engine.defaultPath) + this.key + engine.defaultSuffix], this.template);
require([engine.defaultRequireTextPluginName + "!" + addTrailingSlash(engine.defaultPath) + this.key + engine.defaultSuffix], function(templateContent) {
this.retrieved = true;
this.template(templateContent);
}.bind(this));

this.requested = true;
}

Expand Down Expand Up @@ -60,6 +66,23 @@
}
};

//override renderTemplate to properly handle afterRender prior to template being available
engine.renderTemplate = function(template, bindingContext, options, templateDocument) {
var templateSource = engine.makeTemplateSource(template, templateDocument),
existingAfterRender = options && options.afterRender;

//wrap the existing afterRender, so it is not called until template is actuall retrieved
if (typeof existingAfterRender === "function" && templateSource instanceof ko.templateSources.requireTemplate) {
options.afterRender = function() {
if (templateSource.retrieved) {
existingAfterRender.apply(this, arguments);
}
};
}

return engine.renderTemplateSource(templateSource, bindingContext, options);
};

//expose the template engine at least to be able to customize the path/suffix/plugin at run-time
ko.amdTemplateEngine = engine;

Expand Down

0 comments on commit 965e735

Please sign in to comment.