D
D
Dmitry Dobrodelov2015-02-11 17:39:33
Template Engines
Dmitry Dobrodelov, 2015-02-11 17:39:33

How to catch html build event based on handlebars template?

Using Ajax, I load a certain set of data from the server, then I build html according to the handlebars template using this data and display it to the user:

$.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(msg){
                var src   = $("#cards-templ").html();
                var templ = Handlebars.compile(src);
                var html = templ(msg.data);
                $('.cards').html(html);
        },
        error: function(msg){
            if (debug) console.log('Error: ', msg);
        }
    });

<div class="cards">
            <script id="cards-templ" type="text/x-handlebars-template">
                    {{#each cards}}
                    <div class="item">
                        <img src="{{image}}" alt="{{name}}">
                    </div>
                    {{/each}}
            </script>
        </div>

Question: how to catch the event when the content is rendered and inserted into .cards so that other features can be applied on it, such as sliders, etc.?
The logical option is that handlebars have nothing to do with it at all and you need to catch some kind of .cards update event, but I don’t understand how to do it?
Searched for possible handlers for .html() but didn't find anything.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Dobrodelov, 2015-02-11
@alt3rmann

I think I found a solution:
Redefine the jQuery .html() function:

(function ($) {
    // create a reference to the old `.html()` function
    var htmlOriginal = $.fn.html;

    // redefine the `.html()` function to accept a callback
    $.fn.html = function(html,callback){
        // run the old `.html()` function with the first parameter
        var ret = htmlOriginal.apply(this, arguments);
        // run the callback (if it is defined)
        if(typeof callback == "function"){
            callback();
        }
        // make sure chaining is not broken
        return ret;
    }
})(jQuery);

And now we change the content addition a little and set the handler:
$('.cards').html(html, function(){
                    console.log("Данные успешно загружены и отображены");

                });

owlCarousel and other scripts work fine.
Similarly, you can make preloaders to download such content.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question