I have built a site which requires user to login. Now I have decided to make content available without logging in but some operation require user to login first. The site heavily depends on Javascript. If user click some button, login form should be popped-up.
What I am planning to do is to attach click event with required buttons so as to check if user is logged in.
Previous code:
$('body').on('click','.editRating',function(){
// code to edit
return false;
})
This is i am planning. To attach one more event handler to required button to check login.
$('body').on('click','.editRating',function(){
if user is not loggedIn{
popup loginForm
return false
}
})
$('body').on('click','.editRating',function(){
// code to edit
return false;
})
So
does this guarantee execution of event-handlers in the same order as defined?
Is there a more cleaner and safe way of achieving the goal?
You could just put it all in one event handler:
If that won’t work, then you could take advantage of capture phase vs. bubble phase in event handling to insure that you get the order you want. I believe jQuery only does bubble phase (although I welcome correction if I’m wrong about that, of course). So you will have to ditch the jQuery
on()stuff in favor of generic JavaScriptaddEventHandler()stuff.(Note that
addEventListener()isn’t in IE 8 or earlier, so if you need to support those browsers then you will need to check foraddEventListener()and, if it does not exist, useattachEvent()instead. See the relevant MDN documentation.)http://jsfiddle.net/WdtsL/ shows how you might do this (minus the IE 8 support just mentioned). Ancestor element capture phase handlers all fire before the child element bubble phase handlers. So you can put your click event handler that checks for login on the
bodytag or any outer container in capture phase. Then the individual buttons can handle clicks normally in bubble phase.Example HTML:
Corresponding example JavaScript: