jsbeautify jquery chaining
I'm using jsbeautifier via the command line (http://jsbeautifier.org/) and it works brilliantly other than it cats my longer jquery chained statements:
$('#foo').closest('div')
.closest('input')
.val();
to:
$('#foo').closest('div').closest('input').val();
Obviously, thats a bit simple, but sometimes the chaining gets a little longer or its an if-statement like this:
if ((foo === bar) &&
c > 5 &&
d != 2)
where it ends up as:
if ((foo === bar) && c > 5 && d != 2)
Has anyone experienced this and modified the beautifier or know of a workaround or alternate parser (I use VIM so I'd prefer not to use an IDE solution like aptana unless it could be called via command-line)? Or do I need to just adjust my code to avoid long if-conditions (and whats the best way t开发者_如何学JAVAo abstract that into something more readable if thats the case)?
Thanks!
Long if-conditions are quite difficult to read back and debug. You could try the following:
var matchesBar = (foo === bar),
greaterThenFive = (c > 5),
notTwo = (d != 2);
if (matchesBar && greaterThenFive && notTwo) {
// Do stuff
}
If you give the variables meaningful names you separate out the working out of the truthy parts and their comparison, and the if
statement is slightly easier to read.
It doesn't directly answer your question re: jsbeautifier but it might help with legibility if there's no other workaround.
You can pass -B
or --break-chained-methods
in your command line to preserve those line breaks.
For if
and other statements, use -w
or --wrap-line-length
to break them once the limit is reached.
From the source
-B, --break-chained-methods Break chained method calls across subsequent lines
-w, --wrap-line-length Maximum characters per line (0 disables) [250]
Other than that, depending on your code, it is always preferential to not have long if
or any statement for that matter. I personally try to stick within the 80-char limit but occasionally have to accept longer statements (especially when dealing with legacy projects).
精彩评论