CoffeeScript - jQuery



jQuery is a fast and concise library/framework built using JavaScript created by John Resig in 2006 with a nice motto − Write less, do more.

jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. Visit our jQuery tutorial to know about jQuery.

We can also use CoffeeScript to work with jQuery. This chapter teaches you how to use CoffeeScript to work with jQuery.

Using CoffeeScript with jQuery

Though jQuery solves the browser issues, using it with JavaScript which have some bad parts is a bit problematic. Using CoffeeScript instead of JavaScript is a better idea.

Keep the following points in mind while converting the to be while using jQuery with CoffeeScript.

The $ symbol indicates the jQuery code in our application. Use this to separate the jQuery code from the scripting language as shown below.

$(document).ready

There is no need of using braces in in CoffeeScript except while calling the functions with parameters and dealing with the ambiguous code and we have to replace the function definition function() with an arrow mark as shown below.

$(document).ready ->

Remove the unnecessary return statements, since CoffeeScript implicitly returns the tailing statements of a function.

Example

Following is an JavaScript code where <div> elements are being inserted just before the clicked element −

<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").click(function () {
               $(this).before('<div class="div"></div>' );
            });
         });
      </script>
		
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
	
      <p>Click on any square below:</p>
      <span id = "result"> </span>
		
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
		
   </body>
	
</html>

Now, we can convert the above code into CoffeeScript code as shown below

 <html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src="http://coffeescript.org/extras/coffee-script.js"></script>
	  
      <script type="text/coffeescript">
        $(document).ready ->
          $('div').click ->
            $(this).before '<div class="div"></div>'
            return
          return
      </script>
		
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
	
      <p>Click on any square below:</p>
      <span id = "result"> </span>
		
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
		
   </body>
	
</html>

On executing, this gives you the following output.

What is Callback?

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks.

For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

Blocking Code Example

Create a text file named input.txt having following content

Tutorials Point is giving self learning content 
to teach the world in simple and easy way!!!!! 

Create a js file named main.js which has the following code −

var fs = require("fs");  
var data = fs.readFileSync('input.txt');  
console.log(data.toString()); 
console.log("Program Ended");

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Tutorials Point is giving self learning content 
to teach the world in simple and easy way!!!!! 
Program Ended

Non-Blocking Code Example

Create a text file named input.txt having following content

Tutorials Point is giving self learning content 
to teach the world in simple and easy way!!!!! 

Update main.js file to have following code −

var fs = require("fs");  
fs.readFile('input.txt', function (err, data) { 
  if (err) return console.error(err); 
    console.log(data.toString()); 
}); 
console.log("Program Ended");

Now run the main.js to see the result −

$ node main.js 

Verify the Output.

Program Ended 
Tutorials Point is giving self learning content 
to teach the world in simple and easy way!!!!!

These two examples explain the concept of blocking and non-blocking calls. The first example shows that the program blocks until it reads the file and then only, it proceeds to end the program, whereas in the second example, the program does not wait for file reading but it just proceeded to print "Program Ended".

Thus, a blocking program executes very much in sequence. From programming point of view, its easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution.

Advertisements