DaveOnCode
coder and technology lover
coder and technology lover
Dec 10th
Due to the growing diffusion of tools to compress and optimize JavaScript files (such Google Closure), I feel the need of an introduction of a standard way to identify and differentiate them (compiled files) from other uncompressed files. Basically, I would adopt a different file extension like CJS (which stands for compiled/compressed JavaScript). In this way it would be easy to browse a directory of hundreds of js files and identify those which are ready to be used in our project because already compressed and optimized.
What do you think about?
Dec 1st
I will repeat it until the dead, the real power of Goolge Closure is the mechanism and the tools behind it, not the classes and methods written for you, but the possibility to write your own better JavaScript code! Today I’m gonna show you how to create and use your custom JavaScript classes and to take the benefits of goog.provide() and goog.require() methods.
Ok, let’s suppose we are working on a funny and exciting project, like an online JavaScript game called “Js Monsters Battle” and let’s suppose the domain will be www.jsmonstersbattle.com. We love OOP, we love write js code, we love to have a well organized and document code, so we will begin by creating our packages, following the standard which establishes that the root of a package must be the reversed domain name, so in our example we will create this folders structure “/com/jsmonstersbattle/” and inside we will put our classes (and subpackages).
Since our game is a game about monsters, we will create the core package “monsters” in that directory and we will write the first base class called Monster. We will got the following: “/com/jsmonstersbattle/monsters/monster.js”, three folders and one js file. Yes, one JavaScript file for class, forget those huge files containing millions of functions, we are going to write better JavaScript code and thinking more like a Java developer. If you are concerning about file size and performances, don’t worry about it, the compiler will reduce and optimize the code for you (just before release the project). Ok, let’s take a look inside the Monster class (monster.js):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | goog.provide("com.jsmonstersbattle.monsters.Monster"); /** * A common Monster * @constructor * @param {String} name * @param {String} age * @param {Number} level */ com.jsmonstersbattle.monsters.Monster = function(name, age, level) { /** @private */ this._name = name; /** @private */ this._age = age; /** @private */ this._level = level; } /** * Returns an amount of damage points * @return {Number} */ com.jsmonstersbattle.monsters.Monster.prototype.attack = function() { return Math.round(this._level + this._age / 100) * 2000; } |
In the code above I defined a basic class called Monster, which is available under the package (namespace) com.jsmonstersbattle.monsters, declared using goog.provide(), then I created a constructor (by using the special jsDoc notation /** @constructor */) which receives three arguments and sets three private Monster’s variable (/** @private */), finally I defined a method attack which returns a number of damage points. Ok, by following the Monster’s example, we can now create as many classes and packages as we like, interfaces (using /** @interface */ and /** @impements */) and subcalsses (using the method goog.inherits()), let’s see briefly these implementation:
Extending a class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * @constructor * @extends com.jsmonstersbattle.monsters.Monster */ com.jsmonstersbattle.monsters.UglyMonster = function(name, age, level, uglyness) { // call to Super com.jsmonstersbattle.monsters.Monster.call(this, name, age, level); /** @private */ this._uglyness = uglyness; }; // you can read the following as: "UglyMonster extends Monster" goog.inherits(com.jsmonstersbattle.monsters.UglyMonster, com.jsmonstersbattle.monsters.Monster); |
Creating and implementing an interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /** * Evil interface. * @interface */ function IEvil() {}; IEvil.prototype.doEvil = function() {}; /** * @constructor * @implements {IEvil} */ com.jsmonstersbattle.monsters.EvilMonster = function(name, age, level) { // some code here }; com.jsmonstersbattle.monsters.EvilMonster.prototype.doEvil = function() { // IEvil implementation } |
Once we created all the necessary classes, we will put our “com” folder under “closure” folder. Then we will create a main js file which will includes all the code required to initialize and run the application, I called it “application.js” for convenience. This file will requires all the classes it needs by using goog.require():
1 2 | goog.require("com.jsmonstersbattle.monsters.EvilMonster"); // ...and so on! |
After the import we will be able to use the classes, by referring them with the full qualified class name (“com.jsmonstersbattle.monsters.EvilMonster”), however since this means to write long strings, we can create references as the following:
1 2 3 4 5 6 7 | goog.require("com.jsmonstersbattle.monsters.EvilMonster"); var EvilMonster = com.jsmonstersbattle.monsters.EvilMonster; // then... var monster = new EvilMonster(); |
or use the JavaScript with operator:
1 2 3 4 5 6 7 | goog.require("com.jsmonstersbattle.monsters.EvilMonster"); with (com.jsmonstersbattle.monsters) { var monster = new EvilMonster(); } |
…and this is all today, I hope you enjoyed my post ;^)
UPDATE:
Don’t use the with operator nor take reference to fully qualified class name, otherwise you will get several errors if you use advanced compilation!
Nov 26th
By using Closure’s NumberFormat class (located under goog.i18n package) is relatively easy to format numbers and print readable strings. All we have to import is goog.i18n.NumberFormat:
1 2 3 | <script type="text/javascript"> goog.require("goog.i18n.NumberFormat"); </script> |
Then, we have to create an instance of that class and specify the type of format to apply, by choosing among: CURRENCY, DECIMAL, SCIENTIFIC and PERCENT. Assuming we have to display a budget, we will write a similar statement:
1 2 3 4 5 | // create a new formatter var formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.CURRENCY); // test the output console.log(formatter.format(15650.579)); |
The code above, by using the default locale, will print: $15,650.58. Is possible to localize the output by assigning a different symbols set to goog.i18n.NumberFormatSymbols. The code below will set an italian format:
1 2 3 4 5 6 7 8 | // symbols setting goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it_IT; // redefine formatter (in order to use new symbols set) formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.CURRENCY); // see the differences console.log(formatter.format(15650.579)); |
This time the output will be: € 15.650,58.
Nov 23rd
As I said on insideRIA, the power of Google Closure is represented by the additional tools provided by Google: the Java compiler (which compress and optimize your javascript files) and the python script (which calculates dependencies). This tools however are not so user friendly, because you have to rely on the terminal and invoke them through command lines, a pretty annoying procedure that can scare people which usually rely only on visual tools.
Fortunately is relatively easy to automatize this compilation, by using Ant (a Java-based build tool). Ant is included by default in Eclipse standard platform (anyway some stand alone Eclipse-based ide such Aptana don’t include it… it’s time to use such programs as Eclipse plugins!) and can be configured and used by simply writing an xml file formally named “build.xml“. A build file contains one root node “project” and at least one “target” node containing tasks to execute, tasks are a series of different operations that can be executed by Ant, such create/delete files and folders, zip/unzip a file, running scripts and more. To automatize the deployment of our JavaScript application, we will invoke the calcdeps.py and the compiler.jar from Ant in a single statement, and we will print the result to a specific file.
To invoke a script, we have to use the exec tag and specify at least the param “executable“, which indicates the location of the script to execute, then by setting the parameter “output” the result returned from the script will be redirect to the specified file. Finally, to avoid undesired output in the file, such debug information and errors, we have to specify also a file which will receive this type of data by using the “error” parameter.
Since, paths to scripts and other files can be very long, we can create custom variables to hold these information and then reusing them in our script invocations. This is as simple as use the “property” tag and specify a “name” and a “value” attributes.
The following is an example of how a build.xml will looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?xml version="1.0" encoding="utf-8"?> <project name="Google Closure Ant Test" basedir="." > <!-- Full path of the current project --> <property name="projectPath" value="/Users/davidezanotti/Documents/workspace/GoogleClosure" /> <!-- Full path to Closure library --> <property name="closurePath" value="${projectPath}/closure" /> <!-- List of javascript files to compile --> <property name="filesToCompile" value="${projectPath}/my-closure-app.js" /> <!-- Full path to the compiler jar --> <property name="compilerPath" value="/Users/davidezanotti/Documents/closure-compiler/compiler.jar" /> <!-- Full path to the compiled file (created if not defined) --> <property name="outputPath" value="${projectPath}/ant-generation.js" /> <!-- Full path to the file which will contains debug output and errors --> <property name="logPath" value="${projectPath}/closure-compiler.log" /> <!-- Compilation level --> <property name="compilation" value="WHITESPACE_ONLY" /> <target name="JavaScript Compilation"> <exec error="${logPath}" output="${outputPath}" executable="${closurePath}/bin/calcdeps.py"> <arg line="-i ${filesToCompile} -p ${closurePath} -o compiled -c ${compilerPath} -f '--compilation_level=${compilation}'" /> </exec> </target> </project> |
The build.xml above will first gathering all the necessary Closure files (dependencies) and then will compile the resulting js using a WHITESPACE_ONLY compilation. The result will be printed to the file “ant-generation.js” and the debug to “closure-compiler.log”.
To run the Ant process: right click on the build.xml and choose Run as Ant Build. This procedure can be also configured in order to execute all the task each time a file in the project is saved, but it’s not a great idea because the process can takes several seconds to complete.
If you want to learn more about Ant (I have to learn a lot too, since I never used it before :P), check the reference here: http://ant.apache.org
Nov 17th
Closure has a consistent package called goog.net, which contains a lot of classes to work with ajax and remote http requests. In this post I want to show how to create a basic xhr object to make get/post calls, listen for related ajax events and send data to server. Once imported the main js file (base.js), we will require the following:
1 2 3 4 | goog.require("goog.dom"); goog.require("goog.net.XhrIo"); goog.require("goog.structs.Map"); goog.require("goog.Uri.QueryData"); |
The most important import is goog.net.XhrIo, which represents the object wrapping the XmlHttpRequest and allows us to retrieve and send information to/from the server. This class is a pretty low level api, which means that several tasks are not as simple and automatic as they would in jQuery or such libraries, but on the other hand this offers us more control and consciousness of what we are going to do.
The first step is instantiate an object of type goog.net.XhrIo and take a reference to it:
Nov 16th
Hi everyone,
by starting with this post I would like to begin a series of posts dedicated to the new javascript library released by Google: Closure!
Today I will focus my attention on tabs creation, since this is maybe the most common user interface component in a web application.
In order to create Closure tabs, we need to import the base js file (/goog/base.js) and then require the class goog.ui.TabPane. Inside our head (or body) we will get the following:
1 2 3 4 | <script src="closure/goog/base.js"></script> <script type="text/javascript"> goog.require('goog.ui.TabPane.TabPage'); </script> |
Nov 4th
Recently I’ve updated my Eclipse version and I installed certain plugin which has created some kind of conflict and confusion in my workspace. What I was trying to do was installing an SVN plugin in order to work on a google code SVN repository, but I had several errors and I lost several hours trying to figure out what was wrong. So I decided to do a fresh and clean installation, once understood the problem. So, I would like to write a sort of tutorial which will explain how to get a sound and working installation of Eclipse, Aptana and Subclipse (which as far I read, is actually the best plugin available for SVN on Eclipse).
Oct 29th
In these days I worked on a project into which I have to rely on SSI (apache’s Server Side Includes) in order to read and use url parameters to dynamically include certain html files with “include virtual” directive. Unfortunately the documentations available online is not exhaustive, and I had to figure out some things by myself.
Anyway, according to the docs, there are several global variables we can use in SSI, two of these are: DOCUMENT_URI and QUERY_STRING, which are the two we can use to handle the page url. The first returns the (%-decoded) URL path of the document, the second all the string starting with “?”.
So, how we can extract our desired variables from these strings, since SSI doesn’t offer method such “substring”, “split”, “indexOf” and similar? The answer is: by using Regular Expression in a tricky and ingenious way!
SSI offers a basic way to implementing decision flow (if, else, elif), the if command has an attribute expr which represents a declaration to be valuated, in this attribute is also possible to use a regex to test a given pattern. By knowing this, is possible to declare an SSI variable which represents the desired querystring parameter in the following way:
1 2 3 4 5 6 7 | <!--#if expr="$QUERY_STRING = /year=([0-9]{4})/" --> <!--ssi-comment: year found --> <!--#set var="year" value="$1" --> <!--#else --> <!--ssi-comment: year NOT found --> <!--#set var="year" value="$DATE_LOCAL" --> <!--#endif --> |
In the code above I’m looking to a querystring parameter called year which must be a 4 ({4}) digit number ([0-9]).
If the pattern tested returns true, the matched value (returned by the regex) will be assigned to the SSI variable year, otherwise the current server date year ($DATE_LOCAL) will be assigned.
Notes:
1. “ssi-comment:” is not a special syntax, but just a comment style I decided to adopt to be readable and understandable.
2. To get only the year from $DATE_LOCAL variable, you must config the format using “#config timefmt=”%Y”"
Sep 10th
I’m working on a personal big project (which I’m going to release soon) and in this project I need to parse strings containing XHTML tags with the goal of extract the top level of a given tag name, ie. from:
1 2 3 4 5 6 7 8 9 | <onetag id="t1"> <onetag id="t1-1"></onetag> <onetag id="t1-2"></onetag> </onetag> <onetag id="t2"></onetag> <onetag id="t3"></onetag> <onetag id="t4"> <onetag id="t4-1"></onetag> </onetag> |
I have to get 4 tags (t1, t2, t3, t4 with t1 and t4 containing their child nodes).
My regex knowledge is unfortunately very basic, so I googled for a ready to use regex, but none satisfied my need… all the examples I found didn’t handle properly nested tags… so, after some hours of testing I realized my own regex (my first real one), the result is the following:
1 | var pattern = /<(onetag)[^<>]*>(<\1[^<>]*><\/\1>)*<\/\1>/gi; |
In my case I’m using that pattern in Javascript, but I think it can be used with any language, because it doesn’t make use of advanced features like “atomic grouping” and these kind of “black magics”. To match the desired tag you can use it by replacing “onetag” with the tag you are looking for (even a tag with a namespace like “<foo:mytag>”).
EDIT:
The pattern above will work only if applied to a single line string (ie: var myString = “<onetag id=’t1′>…”), if you use that pattern on a “complex string” (a string containing spaces and new lines) it won’t works properly. Fortunately you can remove “bad characters” before by using a simple replace:
1 | var parsedString = originalString.replace(/\s(?!\w)/gi, "").match(pattern); |
\s(?!\w) will match any space and new line not followed by an alphanumeric characters (in this way spaces between tag attributes won’t be removed)
EDIT 2:
The pattern /<(onetag)[^<>]*>(<\1[^<>]*><\/\1>)*<\/\1>/gi won’t works properly in presence of several type of nested tags, ie:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <onetag id="t1"> <anothertag> <onetag id="t1-1"></onetag> <onetag id="t1-2"></onetag> </anothertag> </onetag> <onetag id="t2"></onetag> <onetag id="t3"></onetag> <onetag id="t4"> <anothertag> <onetag id="t4-1"></onetag> </anothertag> </onetag> |
The updated pattern is the following:
1 | var newP = /<(onetag)[^<>]*>.*?(<\1[^<>]*>.*?<\/\1>)*.*?<\/\1>/gi; |
I hope this will works without further modifications :P
Aug 25th
This is just a quick post to share these 2 little shortcuts to convert text from lower case to uppercase and viceversa in Eclipse.
Lower case: CTRL+SHIFT+Y
Upper case: CTRL+SHIFT+X
In both the combination you can select one or more character to convert.
Recent comments