I'm doing some JQuery stuff and for a person of simple tastes the readability of nested function() definitions all written on one line is very poor. Debugging is a pain in the arse. So here's some modest proposals for maintanable code:
- Assign callback functions to variables
- Use the variable in place of the function (){...}
- Format them as you would if it was a function with all the relevant curly braces and indents
This adds a few characters of 'weight' to the page, but these can be minified away for production code.
Here's how I would do it:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var showmess="Show";
var hidemess="Hide";
var show=function()
{
$('p').toggle();
if($('#showlink').text()==showmess)
{
$('#showlink').text(hidemess);
}
else
{
$('#showlink').text(showmess);
}
}
$(document).ready(
function()
{
$('p').hide();
$('#showlink').text(showmess);
$('a').click(show);
})
</script>
</head>
<body>
<h1>Hello</h1>
<p>You can't see this</p>
But you can see this.
<a href="#" id="showlink"> </a>
</body>
</html>
As you can see I'm a bit of a traditionalist with my curly braces. My training manual when I started c programming was K&R C Programming Language and I've never really got out of the habit of matching brace indents.
No comments:
Post a Comment