8

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.

Ricardo Polo Jaramillo
  • 12,110
  • 13
  • 58
  • 83
Hector Villarreal
  • 822
  • 10
  • 20

3 Answers3

2

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(); });
    });
    
Tom Fakes
  • 955
  • 5
  • 12
0

This will work perfect:
All you need to do is include your script after completion of pjax request.

Include Pjaxstandalone.js here then 

<script type='text/javascript'>
    pjax.connect({
        'container': 'content',
        'beforeSend': function(){console.log("before send");},
        'complete': function(){
            console.log("done!");
           // Your custom script here
         }
    });
</script>

Hope it helps..!!

Abhishek Goel
  • 18,785
  • 11
  • 87
  • 65
0

Ok, learned a couple of things yesterday.

First, declaring coffeescript like that will make the code available only to that file and not accessible anyplace else.

The common way around this is, for example

Users =
   aMethod: -> 
      // some code


window.Users = Users

then in some other place you can do

window.aMethod

anyway, that was just part of the problem, the real solution was using the delegate http://api.jquery.com/delegate/ method, which allows you to bind elements without them being there.

Hector Villarreal
  • 822
  • 10
  • 20