1

I'm working on a system that fetches pages dynamically using AJAX. The pages are fetched like so (index.php):

//Call destructor if any...
//This is defined in the page that we request
if (window.MyModule)
{
    window.MyModule();
    delete window.MyModule;
    window.MyModule = undefined;
}


$('#content').load('requestHandler.php', {'val': index
                                      },
                                      function ()
                                      {
                                        $('#content').fadeIn();
                                      });

Where #content is the div ID of the container (index.php):

<div class="container-fluid" id="content">
   Content comes here as we click on different hyperlinks...
</div>

The pages that are going to be displayed is returned by the php-script requestHandler.php which takes the index and looks up the right page. This works fine if I click a hyperlink once. If I click the hyperlinks twice or more than that I end up with multiple event handlers for the different click events on the page. Due to this I run the destructor function on the page I fetch which look like so, before I request a new page (home.php):

<ul id="report" class="nav nav-tabs" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home_tab" data-toggle="tab" href="#home" role="tab">Home</a>
  </li>
</ul>  


<!-- Tab panes -->
<div class="tab-content">
    <div class="tab-pane active" id="home" role="tabpanel">
        <div class="row"> 

          <div class="col-md-4 text-center">
          </div>

           <div class="col-md-4">
               <div id="line_header" style="visibility: hidden;">
                   <h1 class="display-4 text-center cliente">Linjevalg</h1>
                      <div class="list-group" id="route_list" style="overflow-y: auto;">

                      </div>
               </div>
           </div>

           <div class="col-md-4 text-center">

           </div>
        </div>
    </div>

</div>


<script>

        window.MyModule = (function ()
        {

            var value = undefined;

        $(document).on( "click", "#route_list .list-group-item", function()
        {
            //Handle click event in here
            console.log("We are handling this!");
        });


        function destructor()
        {
            $("#route_list .list-group-item").off('click');
        }

        return destructor;

      })();
</script>

I have been looking at the examples found here: Can dynamically loaded JavaScript be unloaded?.

But whatever I do the click event fire the same amount of times as the same page is requested even if I call the destructor function. Does this mean that since the same DIV id is assigned multiple times (due to that the same page is rendered) all click-event handlers will be invoked since it already knows about the div ID? The pages are by the way loaded by returning the content from (requestHandler.php):

    ob_start();
    include indexToPageName(index);
    return ob_get_clean();

since they contain PHP-code.

Thanks for any help or guidance!

Community
  • 1
  • 1
Araw
  • 2,410
  • 3
  • 29
  • 57
  • How are the blocks of javascript related? It seems to me you only need the click handler and the load section, the rest is unnecessary. – jeroen Feb 10 '17 at 07:50
  • @jeroen: Thanks for your reply. The javascript code on the top is javascript that is in the index.php (the page that is always displayed). So when a user clicks on a hyperlink that block of javascript code is fired. Which loads the requested page in to the content div. So the first two code blocks above are related, while the third is the requested page. Hope that answered your question. – Araw Feb 10 '17 at 07:56
  • So the `window.MyModule` part is in the page that is loaded by `index.php`? If that is the case, you should move that to `index.php` as there is no need to load that more than once. – jeroen Feb 10 '17 at 08:04
  • @jeroen: Yes, that is correct. The plan was to exclude "unnecessary" code since it may not be that user request for that page, hence the Javascript code will never be used. But I guess you're right, there is no way to exclude that part since it will be loaded a new instance for each time the page is requested? – Araw Feb 10 '17 at 08:08
  • I don't know what amounts of code you are talking about, but a minimized, cached version of an external javascript file can very well be more efficient than different script blocks in different files. But even so, you don't have to move everything, the click handler is the most important as you want that always and only once. – jeroen Feb 10 '17 at 08:10
  • 1
    @jeroen: I will try to do as you suggest. Thanks for your help! Provide it as an answer and I will accept it. – Araw Feb 10 '17 at 08:12

2 Answers2

2

There is no need to bind a click hander in every new file that you load. As you use event delegation:

$(document).on( "click", "#route_list .list-group-item", function() {
    ...
}

you only have to execute this once and all clicks on a #route_list .list-group-item item will trigger your click handler correctly.

So by moving the click handler to index.php you solve your problem and you reduce the amount of code you have to maintain.

jeroen
  • 91,079
  • 21
  • 114
  • 132
0

I think you are trying to do something like this. that whenever you click element it has to bring it's own content? You can trak what are you clicking by "this".

$(document).ready(function() {
  $(document).on( "click", ".linking", function(){
   console.log(this);
    console.log($(this).html());
    //Handle click event in here
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>          
  <li class="linking">Home</li>
  <li class="linking">About</li>
  <li class="linking">Contack</li>
</ul>
Janatbek Orozaly
  • 445
  • 3
  • 17