Showing posts with label CoffeeScript. Show all posts
Showing posts with label CoffeeScript. Show all posts

Saturday, February 23, 2013

CoffeeScript and JQuery

Writing JQuery code with CoffeeScript was bit of a Challenge for me. I sort of had to unlearn my previous coding habits so not to make my CoffeeScript look like JavaScript. With me its more of a coding style problem but overall writing DOM manipulation code with CoffeeScript (with JQuery) is more pleasant that I expected. It's certainly shorter.

Let's start with the HTML doc that we will be playing with.

<html>  
   <head>  
     <title></title>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <link href="css/mystyle.css" rel="stylesheet">  
     <script src="js/jquery-1.9.1.js" type="text/javascript"></script>  
     <script src="js/Control.js" type="text/javascript"></script>  
   </head>  
   <body>  
     <div id="hoverElem">Hover over <a href="#" id="target">this</a> to show message</div>  
     <div id="message" class="hidden">I be rollin' with CoffeeScript and   
     they be hatin'!</div>  
   </body>  
 </html>   

It's quite easy to figure out what I'm trying to do here. I have a target "this" when you hover over it, it shows some kind of message.

The CSS is also quite simple.

root { 
    display: block;
}

#message{
    border: 1px solid #9966cc;
    margin: 10px;
    padding: 10px;
    text-align: center;
}

.hidden{
    display: none;
}

The real work is again done with our CoffeScript file.

$ ->
  $('#target').mouseover (e) -> $('#message').removeClass 'hidden' 
    
  $('#target').mouseout (e) -> $('#message').addClass 'hidden'

The first line "$ ->" is equivalent to the document.ready() or $.function() for JQuery. The next two lines are where the work is done. The syntax is quite compact to handle a mouseover and mouseout events. The (e) element is the event parameter. The arrow part leads to inside of the function with the removeClass and addClass methods.

The sample here is quite trivial but it does show the basics of using CoffeeScript with JQuery. A couple of more weeks (or months) of puttering around with it I think I can get pretty good with CoffeeScript and another popular JavaScript libraries like underscore, knockout or maybe gmap.

Can't wait to try this out with a real project. Let's see if Odesk got some. *grin*

Wednesday, January 30, 2013

CoffeeScript prototypes and classes

CoffeeScript tries to overcome the verbosity of JavaScript's prototype and class syntax. Here's how JavaScript does it:

function foo(name){
    this.name = name;
}

foo.prototype.bar = function(){
    console.log('Status is fubar!');
}

o = new foo('John');
o.bar();

That's a bit more of characters to type. If you take a look at how CoffeeScript does it:

foo = (@name) ->                 # the @name is same as writing this.name = name

foo::bar = ->                    # the '::' is the prototype keyword
  console.log 'Status is fubar'
  
o = new foo('John')

console.log o.name
o.bar()

But all this prototype business can be moved into a more object-oriented style using CoffeeScript's class constructs.
class Fish
  constructor: (@name) ->               # gets transformed into a simple JavaScript constructor
  swim: (direction) -> console.log @name + 'is swimming ' + direction # prototype; notice the @name which is this.name
                                                                      # and the direction is a function parameter
  
fish = new Fish('Nemo')   # play around with fish object
console.log fish.name
fish.swim('north')

I sort of subscribe to shorter code is cleaner code. That's why I'm liking CoffeeScript so far.

Sunday, January 27, 2013

CoffeeScript control structures

Coffeescript has really few control structures. Most of the loops, for example, can be written as comprehensions over arrays, objects and ranges. Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, and map.

For example:
fruits = ['Apple', 'Orange', 'Banana', 'Grapes']
console.log fruit for fruit in fruits

Would result in this JavaScript:
var fruit, fruits, _i, _len;

fruits = ['Apple', 'Orange', 'Banana', 'Grapes'];

for (_i = 0, _len = fruits.length; _i < _len; _i++) {
  fruit = fruits[_i];
  console.log(fruit);
}

The real work happens at the console.log fruit for fruit in fruits line. It calls the console.log function for each fruit in fruits.

CoffeeScript also has a few cool tricks in working ranges. They are quite handy if you need row numbers for tables. Here is an example:

tableRowNum = (num for num in [10..1])  
console.log c for c in tableRowNum

The only real loop construct that CoffeeScript has is the while loop. But its better than JavaScript's because it can be used as an expression. It also works nicely with another keyword: the until keyword. For all intents is a while not loop in javascript.

# Econ 101
if this.studyingEconomics
  buy()  while supply > demand
  sell() until supply > demand

So far, CoffeeScript is surprising me. It's certainly not boring me.

Saturday, January 5, 2013

CoffeeScript data types and functions

CoffeeScript's golden rule is "It's just JavaScript". As seen, in the previous entry, it compiles to a 1-to-1 equivalent of JavaScript. This also means that CoffeeScript's data types are also limited to what JavaScript has. These are strings, numbers, booleans, arrays, objects, nulls and undefined values. But CoffeeScript has a couple of pretty cool stuff baked for data types, especially strings. Here is a pair of examples:

name = "Jay" // CoffeeScript doesn't need a var prefix 
greet = "Hello, #{name}" // String interpolation
                         // Result: Hello, Jay

grade = 88.43 
withHonors = 100 <= grade > 85 // chained comparisons
                               // Result: true

songNotes = ["do", "re", 
             "mi", "fa", 
             "so"] // just an array but CoffeeScript knows how to deal with new lines

Also, CoffeeScript takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.

There are a lot more cool/useless stuff baked into CoffeeScript variables but to really use them you need functions. In JavaScript, functions are needed for almost anything. Its the same in CoffeeScript. CoffeeScript just declares functions differently - more lisp/scala like.
// Here is a function without a paramter
foo -> alert('foobar')  // foo is the function name
                        // the part after the "->" is the body of the function

// Here is a function with a parameter
square = (x) -> x * x  

// Here is a function with default value on a parameter
fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."

Friday, December 21, 2012

Installing and working with CoffeeScript in Netbeans

Netbeans Plugin page
Netbeans already has excellent support for JavaScript fortunately it also has a plugin for CoffeeScript written by a guy name Denis Stepanov. Although its missing a "set target folder" feature and only supports CoffeeScript 1.3.3, its still good. The thing here is that it just works. I don't need to install node.js (and the associated npm) to translate CoffeeScript to JavaScript.

To add CoffeeScript support in Netbeans, we start off downloading the plugin. When done you install it via the plugin page. You should restart Netbeans after and that's it. 

After the restart, try creating a new project. There should be a new project type called CoffeeScript Application. And you should be able to add CoffeeScript scripts to existing web projects also. Just remember the limitation that where you wrote your CoffeeScript is also where the output JavaScript will be saved to.

Next post will be about CoffeeScript data types and functions.


Thursday, December 20, 2012

My course to learn the good parts of JavaScript -> CoffeeScript


JavaScript is big. A lot of stuff are now getting built with JavaScript: mobile apps, desktop apps, database shells, etc.

Now, if you write enough JavaScript you will learn that JavaScript is can be a mess especially on large projects. Even if you followed Douglas Crockford's JavaScript the good parts, its quite verbose. This is where CoffeeScript comes in. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. And this is my course for learning CoffeeScript.

My course works out to something like this:

1. Installing and working with CoffeeScript in Netbeans
2. CoffeeScript data types and functions
3. CoffeeScript control structures
4. CoffeeScript prototypes and classes
5. CoffeeScript and JQuery