How to run a callback when Mustache.js has finished rendering template

折月煮酒 提交于 2019-12-05 03:18:54

Not related to mustache, actually it is about jQuery .html().

$('.your_div').html(rendered).promise().done(function() {

// do your stuff

});

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!");
});

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.

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!