Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 551
Jedediah Avatar asked Feb 02 '13 21:02

Jedediah


People also ask

Is mustache a template engine?

Mustache is a logicless template engine for creating dynamic content like HTML, configuration files among other things.

What does mustache render do?

Mustache can be used for HTML, config files, and source code. It works by expanding tags in a template using values provided in a hash or object. You can use Mustache to render templates anywhere include client side and server side environments.

What is mustache script?

Mustache is a web template system with implementations available for ActionScript, C++, Clojure, CoffeeScript, ColdFusion, Common Lisp, Crystal, D, Dart, Delphi, Elixir, Erlang, Fantom, Go, Haskell, Io, Java, JavaScript, Julia, Lua, .


2 Answers

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

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

// do your stuff

});

like image 145
Sacbmcpd Samuel Avatar answered Sep 28 '22 00:09

Sacbmcpd Samuel


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!");
});
like image 27
low_rents Avatar answered Sep 28 '22 02:09

low_rents