Getting Started with CoffeeScript

Note: You may also be interested in “CoffeeScript with WebSQL and jQuery“, which gives more examples of CoffeeScript code.

Lately in web development circles there has been a movement to make Javascript easier for everyone. Well, easier is probably the wrong word.  Lets just say that they want to “modernize” it’s syntax.  A little language has been gaining a lot of attention lately that does just this, and it’s called CoffeeScript.  A quick example of assigned on a condition:

big = true
number = 100 if big

Instead of:

var big = true;
if(big) {
   number = 100;
}

Anyways, this tutorial is about getting the CoffeeScript compiler up and running. To do this, you’re going to need Node.js and the Node Package Manager(NPM).

Step 1: Node.js

Getting Node to install is pretty straight forward. All you need to do is download the latest stable version from here and then run:

./configure
make
make install (may need to run as super user)

Step 2: Node Package Manager

Node Package Manager is the equivalent of EasyInstall for Python. It allows a user to install pre-made programs, like CoffeeScript, easily without worrying about build dependencies or any annoying stuff like that.

If you have Curl installed (most Linux/Mac users will), the easiest way to make this happen is to do the following:

curl http://npmjs.org/install.sh | sh

I personally ran into problems with this because of some permissions errors. If you run into this, check https://github.com/isaacs/npm/blob/master/README.md out which has extensive documentation on how to get around it.

Step 3: Install Coffee

Now that we have all of Coffee’s dependencies solved, you can install CofeeScript by doing:

npm install coffee-script

Step 4: Brew Some Cofee

Let’s make a math object…

math =
	cube: (x) -> x * x * x
	square: (x) -> x * x
 
startNumber = 2
cubeStartNumber = math.cube(startNumber)
squareStartNumber = math.square(startNumber)
alert "Cube: " + cubeStartNumber
alert "Square: " + squareStartNumber

Now, save this file to test.cs and then run coffee -c test.cs on the file. You will get a new file called test.js that looks like:

(function() {
  var cubeStartNumber, math, squareStartNumber, startNumber;
  math = {
    cube: function(x) {
      return x * x * x;
    },
    square: function(x) {
      return x * x;
    }
  };
  startNumber = 2;
  cubeStartNumber = math.cube(startNumber);
  squareStartNumber = math.square(startNumber);
  alert("Cube: " + cubeStartNumber);
  alert("Square: " + squareStartNumber);
}).call(this);

That’s it!

If you run in to any problems during the install process, drop a line in the comments and I’d be happy to help.

SVN Merge Example (Trunk to Branch)

I’m often in the situation where I need to merge changes from the trunk development into a branch.  I can never, EVER, remember the command, so I’m putting in here in hopes that I can reference it again and that other people might find it useful.

svn merge -r x:y svn://repositoryURL/repo/trunk/ .

So, how does it work? X is the revision that you branched at. This can also be the revision that you last merged changes from. Y is the version that you want to merge up to.  In most instances, HEAD is probably what you’re looking for.

Note:  Using –dry-run if you want to see the changes that will be made before actually doing it.  It takes some of the “this is scary” out of merging.

Load Javascript Dynamically With Lazy Load

One of the blessings (or plagues) or the “Web 2.0” revolution is heavy use of Javascript.  Used properly, Javascript can enhance your user experience to nearly the level of a desktop application.  Used poorly, and you’re browser is going to crash and burn.  But this post isn’t about using Javascript, it’s about loading it.

You see, a large amount of web developers don’t think about how their web page is loaded.  They think that no matter where scripts are included, its going to take the same time to load.  Actually, this is true.  What we’re after is an apparent decrease in load time.  When you include Javascript files at the top of your HTML document, as soon as the browser encounters the Javascript it will load and execute it.  The problem here is that loading a Javascript file is a blocking call in most web browsers.  What does this mean to you?  It means that while the Javascript is loading, the rest of your page isn’t.  The apparent page load time has increased.

To get around this problem, some web developers have started including their scripts as the last element in the <body> tag.  Done this way, your entire page loads on to the screen before the Javascript starts to load.  The apparent page load time as decreased.  Yes, the script will still take the same time to download and execute, but now people will see content almost immediately.

But why should you include some Javascript files if you aren’t sure the user is going to make use of them?  Enter Lazy Load.  Lazy Load allows you to easily include Javascript or CSS files on the fly.  This is especially helpful when you have large files that need to be loaded.  For instance, a sweet new carousel for your site.  It’s probably pretty large, and the user is going to have to wait for it anyways.  Using Lazy Load you can decrease your site’s apparent and actual load time.  It’s also small (~800 bytes minified), so you won’t need to worry about the footprint.  Oh, it’s really easy too…

LazyLoad.js('http://example.com/foo.js', function () {
     alert('foo.js has been loaded');
});

Form Ajax : How to Create and Submit a Form Using Ajax

For the longest time, web developers were stuck submitting their forms in the normal way: Click a button, go to a processing page, redirect back.  However, now it is possible to submit a form without ever leaving the page with Ajax.  Ajax stands for Asynchronous JavaScript, which as stated before, basically means you can submit a form without ever leaving the page.

So how do you use form Ajax? First of all, we’re going use a JavaScript library called jQuery.  Don’t be scared of it though, jQuery makes JavaScript easy.  What jQuery allows us to do is use form Ajax without having to muck around with all the tedious JavaScript details (which trust me, is a GOOD thing).   Without further a due, here is how to submit a form with Ajax.

To download the full working code for this, click here.

Form Ajax Step 1:  The HTML Page.

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
<html>
<head>
<title>Form Ajax Tutorial</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//After the document has loaded, it adds the following handlers
//to the web page.
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#myform").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("formProcessor.php", $("#myform").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          $("#formResponse").html(data);
     }
);
return false;
});
});
</script>
<head>
<body>
<h2&gt;Form Ajax Tutorial</h2>
<p&gt; Fill out some information &lt;/p>
<form id="myform">
<input type="text" name="firstName" value="" /><br />
<input type="text" name="lastName" value="" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<div id="formResponse">
</div>
</body>
</html>

For anyone who is used to HTML programming, this should all look very familiar.  The only confusing part is the JavaScript, but I’ll explain that here.  The first bit just includes the jQuery library.  This is crucial for form ajax to work.  The rest of the function is explained below:

  • $(document).ready() – This will add handlers to your web page only after the entire page has loaded.
  • $().submit() – This will catch the click of the submit button so that it doesn’t submit the form the normal way, but the Ajax way instead.
  • $().post() – This is the part that sends out data to the processing file.  It also has a callback function that will modify our page to contain data that the processing file sent back.
  • $().serialize() – Takes our form data and puts it into an easy to parse format.

Form Ajax Step 2:  The Processing Page

1
2
3
4
5
6
7
8
9
10
11
<?php
//Get the information that was sent from the form.
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
 
//Get the unix time stamp.
$unixTimeStamp = time();
 
//Print output for out web page to catch.
echo "Hello $firstName $lastName.  The local unix time is <b>$unixTimeStamp</b>";
?>

The processing page is very important for making form ajax work correctly.  What this file does is catch the data sent by the form, and then prints out some information.  The form is waiting for this information, and then will add it to your page.  Note:  This file is a .PHP file.  You need to be running a web server (or have access to one) that can process php files.

Form Ajax Step 3:  You’re Done!

Form Ajax used to be pretty difficult, but now that their are JavaScript libraries like jQuery, MooTools, and Scriptaculous, it’s easier than ever.  To download the full working code for this example, click here.

Javascript Net PDF Viewer

When trying to view PDF files on the internet, you have a very limited number of choices.  The obvious one is to let the user handle viewing PDFs with something like Adobe Acrobat Reader.  However, some users don’t have Acrobat installed.  Or the file gets downloaded instead.  If you want an easy way to view PDF files online though, look no further than Google Docs.

The Google Docs Javascript PDF Viewer will embed the same javascript pdf viewer that Google Docs uses right in to your page via an IFrame.  It’s really that easy.  It even allows for searching of documents (which is quite handy!).  If this sounds like what you’re looking for, the link is below.

Javascript Net PDF Viewer [Google Docs]

iPhone and iPod Touch Development: Starting Out

Beginning iPhone 3 Development Book CoverLast Christmas I graduated from college.  One of my graduation gifts was a 2nd generation iPod Touch!  At the time, the iPod Touch was one of the coolest things I had ever got.  I immediately started to play with it, and was impressed with it’s ability to know the orientation of the device.  It’s multi-touch support was also impressive.  Probably the coolest part of owning an iPod Touch was that “there’s an app for that” attitude.  The sheer volume of available apps was mind blowing.

After graduation I started grad school, so I didn’t have much time to play on the technical side of iPod Touch and iPhone development.  However, I now have the time, and what follows is my journey on the road to iPod Touch and iPhone development enlightenment.

Getting Started

iPod Touch on top of "Beginning iPhone 3 Development"
The iPod Touch. A little banged up, but still amazing.

Before I even got started with iPhone development, I already ran into a problem:  I don’t own a Mac, nor do I want to own one.  It’s not that I don’t like them.  They’re beautiful machines with top of the line hardware and software, it’s just they’re a little outside my

price range.  So, how does one go about developing for the iPod Touch and iPhone on a Windows machine?  Well, there are a few different options.  Some revolve around Cygwin, while others around VMWare.  There is a good thread going on over at Stack Overflow (here) about it.  Depending on your situation, you may want to just pony up the cash for a Mac Mini, but to each their own.  In my case, I went with one of the methods listed above.

About the Book

The book I’ll be using for this adventure is “Beginning iPhone 3 Development:  Exploring the iPhone SDK” by Dave Mark and Jeff LaMarche.  It was reasonably priced, well reviewed, and had a grapefruit on the cover.  How could I possibly go wrong with this?  While I’ve only read the back cover at this point, the only problem I have with it is that it fails to mention the need for a Mac.  Some people might say “Duh!  Of course you need a Mac for iPhone and iPod Touch development!”, but it’s not always obvious to everyone.

Requirements

As with most development projects, there are a few things you need before you get started.  In the case of iPhone & iPod Touch development, you need the iPhone SDK (also, from this point forward I’m going to start referring to “iPhone & iPod Touch development” as “iPhone development”).  To get at the iPhone SDK, you need to visit http://developer.apple.com/iphone/ and sign up to be an iPhone developer.  It’s free (or has free options), so that’s a relief.

The sign up process seemed fairly painless.  While I’m not a huge fan of having to register and give out personal information, they control the SDK, so I suppose I must do as they say.  Nothing too suprising once you’re through the registration though, except the download is 2.5 GB!!! The worst part is that I have no idea why.  I always thought Netbeans with the JDK/JRE was huge, but this thing blows it out of the water.

Hello World

It’s a programming tradition to learn any new programming language with a simple “Hello World” program.  Even when not programming, some programmers still use “Hello World” to break the ice.  Hardly one to break with tradition, I’m going to be starting with a “Hello World” too, except this time for an entire platform, instead of just a programming language.

After much fumbling around, here are the steps to getting a “Hello World” program started.

  1. Open XCode and select New Project… from the File menu.
  2. Select View-based Application.
  3. Name your project Hello World.
  4. In the Groups and Files window, open the Resources group.
  5. Double Click the file Hello_WorldViewController.xib
  6. With the view now open, browse down the library until you find Label.
  7. Drag the label to the view.
  8. Double Click the label, and type “Hello world!”.
  9. Now go to File, then Save.
  10. Go back to Xcode and select Build, then Build and Run.

Honestly, I expected it to be a bit harder than this.  Next time I’m hoping to make it though chapter 3, where I get to learn how to handle basic user interaction!  As always, any feedback is welcome.

Using HTTPService to get XML results from a server

I’m not a Flex developer, but I’m quickly becoming one.  Recently I was tasked with creating a Flex form, sending it to the server, waiting for a response, and handling things accordingly.  My problem was that I couldn’t figure out how to use my result set that I received from the server.  Turns out, I needed to import a EventResult library, which was the turning point.

The Actionscript

import mx.rpc.events.ResultEvent;

private function thanks(evt:ResultEvent):void{
var dataFromServer:XML = XML(evt.result);
mx.controls.Alert.show(dataFromServer.toXMLString());
}

The Flex

<mx:HTTPService
id=”srv” useProxy=”false”
url=”http://localhost/form.php” method=”POST”
contentType=”application/x-www-form-urlencoded”
resultFormat=”xml” result=”thanks(event); “>
<mx:request>
<name>
{ bname.text }
</name>
<address>
{ baddress.text }

</address>
</mx:request>
</mx:HTTPService>

What happens here is that the HTTPService sends my data to the server, then some new data is returned in XML format.  Important things to remember are the ResultEvent that is passed to the event handler.  Just passing a normal event didn’t do much for me.

Still waiting…. but this time with a measure of patience!

I’ve been waiting for over 3 weeks to hear back from IBM.  I eventually heard from them, when they apologized for taking so long.  All this is understandable as they interviewed a TON of people.  The good news is that they want to offer me a job!  They bad news, is that they can’t give me my offer yet because of corporate red-tape.  It has to finalized, stamped, copied in triplicate, etc, etc.  Either way, I’m very excited to see what they have to offer.

I also got an interesting call today from MSU.  I applied for a position as a web developer there almost a month ago, and got a call to interview today.  I was caught off guard, so I hope I didn’t sound not-interested.  I have an interview with them on 12/15.  I look forward to hearing about the position, hopefully answering some interesting questions, and seeing what they have to offer.  While I doubt they can match IBM’s pay scale, they have other incentives like tuition reimbursement and then like, which make a job there very enticing.

Also, along a different line, I created a URL shortener the other day.  It’s called fwds.me.  It works like any other URL shortener, except faster :)*

That’s all I have for now.  I’ll leave an update when I’ve made some job decisions.

*It’s probably not faster, but it’s at least as fast as most other shorteners.  I use Apache mod_rewrite to handle the url, and then a quick sql query to find out the original URL.