Search code examples
javascriptjqueryevent-bubbling

jQuery / bubbling - how to stop my javascript code for non-logged-in users?


If you load my site and you have no $_SESSION (you are not logged in), I will send you this <head>:

<script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/requires-signup.js"></script>
<script src="/js/core.js"></script>

My core.js file contains the whole site javascript code. For example:

$(document).on('click', '.ajaxload-tab', function(){
   console.log('I shall do the load!');
   return false;
});

However, for non-logged users, this is preceded by the requires-signup.js file, which reads:

$(document).on('click', '.requires-signup', function(){
   console.log('No can do!');
   return false;
});

Now, I'm serving you this element:

<div class="ajaxload-tab requires-signup">CLICK</div>

You click on this element. Your console says: I shall do the load! Why?

EDIT

If I delete the return false; part in the .ajaxload-tab event bind, the code works as expected. However, I can't delete that part, because then it messes other stuff.


Solution

  • Perhaps try using .off() in your requires-signup.js like so

    in core.js:

    $(document).on('click.requires-signup', '.ajaxload-tab', function(){
       console.log('I shall do the load!');
       return false;
    });
    

    in requires-signup.js

    $(document).off(".requires-signup")
    

    http://api.jquery.com/off/

    edit: Or this method, if you don't mind globals

    window.notSignedUp = false;
    
    $(document).on('click.requires-signup', '.ajaxload-tab', function(){
       if (window.notSignedUp) return;
       console.log('I shall do the load!');
       return false;
    });
    

    then set window.notSignedUp = true in requires-signup.js