Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.ready not triggered with pjax

I'm trying out pjax for an app I'm developing but I've kinda hit a wall.

Maybe I'm going about this the wrong way, let me explain.

In the app, I have a main menu on top, with the different sections. Each of the links in this menu are pjax enabled, meaning that only the body of the application will change.

Normally, When you click a link with no pjax, the document.ready method will be triggered. I use this to bind events to buttons like the following example.

here is my users.js.coffee file

loaded = false;
$ ->
  $("#btn_new_user").bind "click", (event) ->
    if not loaded
      @path = $('#btn_new_user').attr("path")
      $("#new-users-container").load(@path)
      loaded = true
    $("#new-users-container").slideToggle()

As you can see in this example, when the "users" page finishes loading, it will bind a button with an event that will load a form into a div and animate it to show it.

However, when I start in a different section of the admin and click on the Users link to show this button, the event is not binded. When I reload the page in the Users section, the document.ready triggers and the button works fine.

Is there a better technique to bind the events to buttons or is there some way to trigger document.ready on pjax?

Thanks.

like image 452
Hector Villarreal Avatar asked Nov 12 '11 08:11

Hector Villarreal


1 Answers

Here's how I'm currently doing this.

  1. Use the delegate binding as indicated here for events.
  2. For other initialization, implement it this way (in raw Javascript)

    window.pjax_load = function() {
      $('#foo').do_whatever();
      ...
    }
    
    $(document).ready(function() {
      // setup events etc
    
      window.pjax_load();
      $('a').pjax( "#container" );
      $('#container').on('pjax:end', function() { window.pjax_load(); });
    });
    
like image 120
Tom Fakes Avatar answered Oct 05 '22 00:10

Tom Fakes