问题
Is there a clean way to define/run a callback function once Mustache.js has finished rendering a template and inserting it into the DOM? For example, something like this:
Mustache.render(template, viewModel, function() {...});
The best I've been able to come up with is counting the number of nodes in my view model that will be inserted into the DOM, and then using setInterval to check if that many nodes exist in the DOM. Once they do, I can then call the function I want. This seems inefficient and potentially buggy to me, but I don't know what else to do.
回答1:
Not related to mustache, actually it is about jQuery .html().
$('.your_div').html(rendered).promise().done(function() {
// do your stuff
});
回答2:
you don't need a callback for mustache.js' render()
function because it is synchronous. jquery's .html()
is synchronous as well.
if you really need a callback (for whatever reason) you can code it by yourself:
var myrender = function(template, viewModel, callback)
{
Mustache.render(template, viewModel);
if(typeof callback === "function")
callback();
}
// usage:
myrender(my_template, my_viewModel, function(){
alert("I can do anything here!");
});
回答3:
If you are also using jQuery you can use:
$("#element").ready(function() {
// do something when Mustache.js has finished rendering
});
Mustache.js has the ability to stream template results. This was described in the project's documentation but was removed recently. I'm not sure if this was intentional but it still appears to work. This describes an optional callback parameter of the Mustache.to_html
function that is called each time a chunk of the template is rendered. Maybe this can help with your problem.
回答4:
You can use something like this:
displayData: function () {
app.renderTemplate("test", app.data, function (returnValue) {
$('.result').append(returnValue);
});
},
renderTemplate: function (templatefile, data, callback) {
var tpl = 'views/' + templatefile + '.mst';
$.ajax(tpl,
{
dataType: "text",
success: function (template) {
var rendered = Mustache.render(template, data);
callback(rendered);
}
});
}
The detailed how-to can be found here: https://www.chaensel.de/mustache-js-return-rendered-result-to-callback-function/
来源:https://stackoverflow.com/questions/14666557/how-to-run-a-callback-when-mustache-js-has-finished-rendering-template