I am using events to manage the ui after users log in and out of a website, when a login occurs a login event is published and when a user logs out a logout event is published.
With this system in place I am trying the idea of small inline bits of javascript to deal with the ui elements which subscribe to the events.
At the top of the page is a login/logout link so I am using the following code for changing the login status
<div id="account_panel" class="signed_out">
<div class="in">
<a href="/account" class="name"></a> | <a href="/account/signout">Sign-out</a>
</div>
<div class="out">
<a href="/account/signin" class="signin">Sign-in</a> | <a href="/account/register" class="register">Register</a>
</div>
</div>
<script>
if (window.jQuery) {
$('body').on('login.account.website', function(event, data){
$('#account_panel').removeClass('signed_out').addClass('signed_in');
if (data)
jQuery('#account_panel .name').text(data.first_name+' '+data.last_name);
});
}
</script>
I have several pieces of code like this, the idea is they are all self contained and do not affect or directly depend on other things, the javascript only relates to the code next to it so it seems sensible to put them together.
The initial state of the html is generated server side to allow the site to function without javascript, a code snipit like this is also contained in its own template file.
I want to carry on using this method for various elements on the site but I am interested to find out if there is a better maintainable method I should be using.
Thanks
I’d argue this method is difficult to maintain, having to track snippets of code scattered over multiple html documents. Why not keep the code in one place and bind to your events only when certain DOM elements are present: