Search code examples
javascriptajaxpjax

reinitialize javascript with pjax on back button


Below "done" callback works well when button is clicked. But with browser back button, done callback is not called again.

$.pjax({
        url: $this.attr("href"), 
        container: '#div-section', 
        push: true
}).done(function() {
        $object.init();                 
});

is there some another way to fire other javascripts on pjax end other than done ( as it does not work )?


Solution

  • Found solution but there can be I guess only one such handler in page -

    $(document).on("ready pjax:success", function(){
            //initialize all javascripts here
    });
    

    EDIT

    Above solution leads to dual bindings on pjax calls, once inside pjax:success followed by second time inside done event callback. To have bindings executed only one on back / forward or on pjax , we can do as below. In this case , globalEventDirection can be used to conditionally bind inside pjax:success leaving init to done in case button was clicked. But with back and forward button, init will be done inside pjax:success

        globalEventDirection = undefined;
        $(document).on("pjax:popstate", function(event){
                globalEventDirection = event.direction;
            });
    
        $(document).on("pjax:success", function(event){
            if(globalEventDirection === "back" || globalEventDirection === "forward" ) {
                //reinitialize javascript                   
                globalEventDirection = undefined;
            }
        });