JavaScript code completition done right? - javascript

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?

I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>

The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Related

Is there a way to tell Google Closure Compiler to *NOT* inline my local functions?

Here's what I'm looking for:
I want to use the wonderful features of SIMPLE mode minification while disabling just one specific feature (disable local function inline).
UPDATE: The answer is NO, it's not possible given my setup. But for me there is a workaround given I am using Grails.
As #Chad has explained below, "This violates core assumptions of the compiler". See my UPDATE3 below for more info.
IN QUESTION FORM:
I'm using CompilationLevel.SIMPLE_OPTIMIZATIONS which does everything I want, except that it's inlining my local functions.
Is there any way around this? For example, is there a setting I can place in my JS files to tell Google Closure not to inline my local functions?
It would be cool to have some directives at the top of my javascript file such as:
// This is a JS comment...
// google.closure.compiler = [inlineLocalFunctions: false]
I'm developing a Grails app and using the Grails asset-pipeline plugin, which uses Google Closure Compiler (hereafter, Compiler). The plugin supports the different minification levels that Compiler supports via the Grails config grails.assets.minifyOptions. This allows for 'SIMPLE', 'ADVANCED', 'WHITESPACE_ONLY'.
AssetCompiler.groovy (asset-pipeline plugin) calls ClosureCompilerProcessor.process()
That eventually assigns SIMPLE_OPTIMIZATIONS on the CompilerOptions object. And by doing so, CompilerOptions.inlineLocalFunctions = true as a byproduct (this is hard coded behavior in Compiler). If I were to use WHITESPACE_ONLY the result would be inlineLocalFunctions=false.
So by using Asset Pipeline's 'SIMPLE' setting, local functions are being inlined and that is causing me trouble. Example: ExtJS ext-all-debug.js which uses lots of local functions.
SO post Is it possible to make Google Closure compiler *not* inline certain functions? provides some help. I can use its window['dontBlowMeAway'] = dontBlowMeAway trick to keep my functions from inlining. However I have LOTS of functions and I'm not about to manually do this for each one; nor would I want to write a script to do it for me. Creating a JS model and trying to identity local functions doesn't sound safe, fun nor fast.
The previous SO post directs the reader to https://developers.google.com/closure/compiler/docs/api-tutorial3#removal, where the window['bla'] trick is explained, and it works.
Wow thanks for reading this long.
Help? :-)
UPDATE1:
Okay. While spending all the effort in writing this question, I may have a trick that could work. Grails uses Groovy. Groovy makes method call interception easy using its MetaClass API.
I'm going to try intercepting the call to:
com.google.javascript.jscomp.Compiler.compile(
List<T1> externs, List<T2> inputs, CompilerOptions options)
My intercepting method will look like:
options.inlineLocalFunctions=false
// Then delegate call to the real compile() method
It's bed time so I'll have to try this later. Even so, it would be nice to solve this without a hack.
UPDATE2:
The response in a similar post (Is it possible to make Google Closure compiler *not* inline certain functions?) doesn't resolve my problem because of the large quantity of functions I need inlined. I've already explained this point.
Take the ExtJS file I cited above as an example of why the above similar SO post doesn't resolve my problem. Look at the raw code for ext-all-debug.js. Find the byAttribute() function. Then keep looking for the string "byAttribute" and you'll see that it is part of strings that are being defined. I am not familiar with this code, but I'm supposing that these string-based values of byAttribute are later being passed to JS's eval() function for execution. Compiler does not alter these values of byAttribute when it's part of a string. Once function byAttribute is inlined, attempts to call the function is no longer possible.
UPDATE3: I attempted two strategies to resolve this problem and both proved unsuccessful. However, I successfully implemented a workaround. My failed attempts:
Use Groovy method interception (Meta Object Protocol, aka MOP) to intercept com.google.javascript.jscomp.Compiler.compile().
Fork the closure-compiler.jar (make my own custom copy) and modify com.google.javascript.jscomp.applySafeCompilationOptions() by setting options.setInlineFunctions(Reach.NONE); instead of LOCAL.
Method interception doesn't work because Compiler.compile() is a Java class which is invoked by a Groovy class marked as #CompileStatic. That means Groovy's MOP is not used when process() calls Google's Compiler.compile(). Even ClosureCompilerProcessor.translateMinifyOptions() (Groovy code) can't be intercepted because the class is #CompileStatic. The only method that can be intercepted is ClosureCompilerProcessor.process().
Forking Google's closure-compiler.jar was my last ugly resort. But just like #Chad said below, simply inserting options.setInlineFunctions(Reach.NONE) in the right place didn't resurrect my inline JS functions names. I tried toggling other options such as setRemoveDeadCode=false to no avail. I realized what Chad said was right. I would end up flipping settings around and probably destroying how the minification works.
My solution: I pre-compressed ext-all-debug.js with UglifyJS and added them to my project. I could have named the files ext-all-debug.min.js to do it more cleanly but I didn't. Below are the settings I placed in my Grails Config.groovy:
grails.assets.minifyOptions = [
optimizationLevel: 'SIMPLE' // WHITESPACE_ONLY, SIMPLE or ADVANCED
]
grails.assets.minifyOptions.excludes = [
'**ext-all-debug.js',
'**ext-theme-neptune.js'
]
Done. Problem solved.
Keywords: minify, minification, uglify, UglifyJS, UglifyJS2
In this case, you would either need to make a custom build of the compiler or use the Java API.
However - disabling inlining is not enough to make this safe. Renaming and dead code elimination will also cause problems. This violates core assumptions of the compiler. This local function is ONLY referenced from within strings.
This code is only safe for the WHITESPACE_ONLY mode of the compiler.
Use the function constructor
var fnc = new Function("param1", "param2", "alert(param1+param2);");
Closure will leave the String literals alone.
See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function

Visual representation of classes and/or objects

recently I started to work on some big project written in php/js.
It is really big and I have constant problem of backtracing what functions are called where.
Is there any tool, that would import all the code files and draw/write connections between classes, objects, functions and such?
Regards
BOUML can create UML diagrams out of your code
http://www.bouml.fr/
old 4.23 version is also free if that is needed
http://download.cnet.com/BOUML/3000-2094_4-10788888.html
I am using Intellij IDEA with the PHP Storm Plugin for my PHP/JS-Projects. There I'm able to right click a function and choose "Find Usage ALT+F7". Now I can see, where this function is getting called.
Intellij IDEA/PHP-Storm is also able to generate UML-Diagrams if needed.
I guess Netbeans, Eclipse+PHP-Plugin do have similar functions [maybe execpt of the uml-generator], if you need an IDE at no costs.

Javascript regex shorthand?

I'm trying to enjoy some of the awesome javascript code golf submissions on anarchy code golf, but I keep seeing things like:
for(;s=readline();)print("h"+/t.*/(s))
...which was the JS winner for: http://golf.shinh.org/p.rb?ttp
I don't understand how that is correct javascript syntax, and I even tried resubmitting that, but it said object is not a function, which is something along the lines of what I would expect to happen.
Was this some kind of glitch or shorthand or something in an older javascript version?
Was this some kind of glitch or shorthand or something in an older javascript version?
More or less, yes. According to that site's version info, it uses SpiderMonkey (Mozilla's JavaScript engine), which used to have the feature that regular-expression objects were callable; that is, that if re was a regular-expression object, then re(...) was equivalent to re.exec(...). That feature was removed in this change, a result of Bug 582717, and that site has since updated to a version that incorporates that removal.

How do I add my own JavaScript libs to ClojureScript?

I want to write a Google Chrome extension, using ClojureScript. With ClojureScript I can use all the Google Closure libs, but afaik access to the Chrome browser is not included in those libs. So I want to wrap all the Chrome stuff in my own JavaScript lib.
So far I tried creating my own jar that has a single JavaScript file that just creates a Foo object and exports the constructor. I'v added this jar to the lib directory of the ClojureScript compiler (which also has for example goog.jar), but so far without luck:
Exception in thread "main" java.lang.IllegalArgumentException: No implementation of method: :-compile of protocol: #'cljs.closure/Compilable found for class: nil
at clojure.core$_cache_protocol_fn.invoke(core_deftype.clj:494)
at cljs.closure$eval1056$fn__1057$G__1047__1064.invoke(closure.clj:187)
at cljs.closure$get_compiled_cljs.invoke(closure.clj:422)
at cljs.closure$cljs_dependencies.invoke(closure.clj:440)
at cljs.closure$add_dependencies.doInvoke(closure.clj:462)
at clojure.lang.RestFn.applyTo(RestFn.java:139)
at clojure.core$apply.invoke(core.clj:602)
at cljs.closure$build.invoke(closure.clj:701)
at user$eval1246.invoke(cljsc.clj:21)
at clojure.lang.Compiler.eval(Compiler.java:6406)
at clojure.lang.Compiler.load(Compiler.java:6843)
at clojure.lang.Compiler.loadFile(Compiler.java:6804)
at clojure.main$load_script.invoke(main.clj:282)
at clojure.main$script_opt.invoke(main.clj:342)
at clojure.main$main.doInvoke(main.clj:426)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:405)
at clojure.lang.AFn.applyToHelper(AFn.java:163)
at clojure.lang.Var.applyTo(Var.java:518)
at clojure.main.main(main.java:37)
Has anyone tried this before?
Take a look at this post from Luke Vanderhart: "Using JavaScript libraries in ClojureScript"
http://lukevanderhart.com/2011/09/30/using-javascript-and-clojurescript.html
Also, this video from Kevin Lynagh: "Extending JavaScript Libraries from ClojureScript"
http://www.youtube.com/watch?v=XfzXFWTT-z0
If I remember Rich Hickeys talk correctly the whole program optimization of the closure compiler needs any library code to adhere to certain coding conventions. I think he also said something of JQuery not doing this but Dojo doing this. I never did this but you might find some useful information here

Ajax applications with perl backend - how to?

There are already questions about the Perl+AJAX, like here, here or here and several others. They're more than 2 years old and I was hoping for some new stuff.
The questions are:
What is the most preferred method today making AJAX apps with a Perl backend?
Are there some active and commonly used Perl modules that help build AJAX based applications?
Something, for the usual workflow:
if clicked this button (or changed this field.. etc),
POST these data to the server,
read the JSON answer,
and update this/these DIV(s) in a DOM... etc.
This question is can be classified as vague, but I'm really lost and need help with this: what is the most common way making AJAX apps in the Perl world, TODAY.
Looking for a helper module that help me build the browser-side javascript.
I found these:
https://metacpan.org/pod/OpenThought
https://metacpan.org/pod/HTML::AjaxTags
https://metacpan.org/pod/CGI::Ajax (but this is CGI based and IMHO not the best for Plack world)
These modules have not been updated for several years. Are they stable and in use? Or are they deprecated and is there some better way? (for the modern Perl technologies - like Plack).
UPDATE
As I read answers, I'm thinking that the main problem is probably in my English. I don't know how to express myself right.
I know Perl. Maybe I'm not an expert, but I wrote several thousand lines of code. I know Dancer, and already write some apps in Mojo...::Lite. Know JSON{::XS} and I know how AJAX works.
Now (for some reason) I prefer using Mason2, with Mason::Plugin::RouterSimple and several other CPAN modules and Moose. Catalyst, Jifty are too big for my needs.
Back to the question:
My favorite JS framework is jQuery, I'm using it in several projects for modal windows, or accordions, tabs etc.
BUT
My main problem is exactly in Sismetic's answer. I don't want to write JavaScript. Don't like it. (Don't know it very well, and hate every language where I must write something like: var arr = new Array(); instead of my #arr)
So, looking for a solution, how I can minimize (or in the ideal world - totally eliminate) the need of writing the JavaScript code. Don't want write into my templates
$('.clickableButton').click(function(e) {
.... etc... etc..
)}
but something like:
$ajax->make_button( -onchange=>$url, -updatedom=>'#thisdiv", some_special_button_description_in_perl );
$tohead .= $ajax->gen_libs();
$tohtml .= $ajax->gen_html();
$jsdocready .= $ajax->gen_jsinitcode();
An in my templates will output only $tohead in the head part (so include jQuery), $tohtml will come into body, and $jsdocready will come into the end of body as JavaScript init code.
Offcourse, the above is an very stupid example, but hopefully shows what I mean. Simply: The ideal solution was (probably does not exists) is totally eliminate the need writing JavaScript, only Perl code what will generate the needed JS.
Therefore I mentioned the above modules, especially https://metacpan.org/pod/OpenThought, because these really help minimize writing JavaScript. The problem is - these have not updated for 2 years. ;( And unfortunately - I don't know any others.
The reason you're not getting answers isn't just the vagueness of the question. The problem space is very wide and has a many angles of attack.
Let's clarify that the "x" in Ajax shouldn't be taken to mean XML anymore. JSON is obviously more natural and doesn't suffer from nearly as many problems so all my advice will point toward it.
What hobbs said already is right on. You do not want to mess with the server-side code much at all but adopt a framework. This is not because dealing with Ajax is hard in Perl; it's trivial. It's because the problem space gets messy quickly and you'll end up repeating your code in endless minor variations. So–
Perl/Server-side
Any of these will make you happy eventually. They all have a learning curve. There are other options but these are the Best™.
Catalyst (Catalyst::View::JSON)
Dancer (Dancer::Serializer::JSON)
Mojolicious (prefer Mojolicious for HTML5/Websockets)
Deployment SHOULD be Plack/PSGI based.
Take the time to really learn the core of Perl's Ajax handling: JSON(::XS) so you know what the views in the various frameworks do under the covers.
JavaScript/Client-side
This is essentially an embarrassment of riches at this point.
jQuery
Many Perl hackers like this kit; it seems to hit the same sweet spot Perl does. I adore jQuery.
Dojo
I'm not a fan — they had the worst documentation possible in early versions and broke compatibility while deleting what little docs used to exist — but it's well-liked in its current version.
MochiKit
MooTools
YUI
ExtJS
This, now distant, fork from YUI is the 800lb gorilla of client-side JS. I personally dislike it because of its lack of graceful degradation, et cetera, but it is highly regarded and very sharp looking out of the box.
I personally dislike and can't recommend prototype and though I've never used it I also chose not to put script.aculo.us on the list.
There are plenty of other amazing specialty kits out there too; e.g., Modernizr. When you are looking into JS, consider how important standards compliance and forward-looking features like CSS3, HTML5, extended event handling like multi-touch are to what you'll do. Good luck and have fun.
Update: Possibly of further interest
Jemplate – templating in JavaScript
Catalyst::View::Jemplate
Jifty – YAWF
Looking for "ajax" isn't really what you need. Just use a web framework of your choice that has good facilities for serialization, working with Accept headers, etc. For example Catalyst and Catalyst::Action::REST, or Dancer. Don't write Perl that writes Javascript, it will only make you sad.
I use CGI::Application as my base framework and CGI::Application::Plugin::JSON to return JSON data to jQuery.
If you want to generate HTML code with a Perl module, I would recommend CGI.pm:
...
use strict;
use warnings;
#CGI is shipped along perl, I think
use CGI;
my $CGI = CGI->new();
my $return_string = '';
#From CGI documentation on CPAN
#http://search.cpan.org/~markstos/CGI.pm-3.55/lib/CGI.pm
$return_string .= $CGI->header;
$return_string .= $CGI->start_html('hello world');
$return_string .= $CGI->h1('hello world');
$return_string .= $CGI->button(-name => 'button_name',
-value => 'Click Me!',
#Javascript event if needed
-onClick => "do_something()"
);
$return_string .= $CGI->end_html;
print $return_string;
Or(as I dont like the latter method) you could just write it on perl(generating it yourself manually):
use strict;
use warnings;
#Needed header, otherwise will return error
print "Content-type: text/html\n\n";
#return random number from 0 to 100
my $random_number = int(rand(101));
my $HTML_generated_string = qq|
<html>
<head>
<title>HTML generated manually with perl</title>
</head>
<body>
<h1>Hello world</h1>
Bla bla bla Heres the random number $random_number
</body>
</html>
|;
print $HTML_generated_string;
Other than that, I dont know any extra modules to do it. I normally do it by hand, or write a template(with CGI::Application).
I don't think the thing you are asking for exists. You can't write AJAX apps without using JavaScript. If someone invented a way to do JavaScript without JavaScript it would be a major project and not one person's weekend CPAN module.
I suggest rethinking your view of JavaScript. JavaScript is an excellent language and JQuery is great as well. There is a lot of bad JavaScript code out there, but there is good JavaScript code as well. Just like there are good and bad practices in the Perl community. I'd suggest you keep an open mind and take another look at JavaScript and make sure you really know the foundations well. Sometimes my frustration with a language just means I haven't learned it very well.
There are some very cool things happening in the JavaScript world. I admit its chaotic and decentralized and there is a lot of different stuff to know about and thats exhausting but its also exciting that so much is happening.
You probably already know about these resources, but just in case: FireBug, Mozilla Developer Network JavaScript docs, and JavaScript Garden
See Dancer::Plugin::Ajax on cpan
http://metacpan.org/pod/Dancer::Plugin::Ajax

Categories

Resources