Coffeescript using the way to summarize _javascript tips

Source: Internet
Author: User
Tags function definition

Coffeescript as a JavaScript low-key little brother is really a good place, use it can improve development efficiency, reduce code errors, the key is to greatly improve the development of pleasure. I feel more and more that I can use the coffee in my project as long as possible.

But perhaps you and I, like me, after understanding the grammar of Coffeescript ready for a try, but faced with how to introduce it into the project and make a worry.

Command your code like a boss.

Coffeescript provides a bunch of cool array iteration methods. The best thing to do is not just to work on arrays, but to work with jquery objects. To do the poetic code:

Formvalues = (Elem.value for Elem in $ ('. Input ')) 

This line of code will be translated into JavaScript as follows:

var elem, formvalues; 
Formvalues = (function () { 
 var _i, _len, _ref, _results; 
 _ref = $ ('. Input '); 
 _results = []; 
 for (_i = 0, _len = _ref.length; _i < _len; _i++) { 
  elem = _ref[_i]; 
  _results.push (Elem.value); 
 } 
 return _results; 
}) (); 

To be honest, it's scary at first to write code, but once you start embracing Coffeescript's magic, you'll love it.

Fly the general method binding

Using the "=>" in the jquery callback will greatly reduce the hassle of manually binding methods to objects. Let's take a look at the code:

Object = 
 func:-> $ (' #div '). Click => @element. CSS color: ' Red ' 

The following is the JavaScript for compiling output:

var object; 
var __bind = function (FN, ME) {return function () {return fn.apply (me, arguments); 
;}; Object = { 
 func:function () {return 
  $ (' #div '). Click (__bind (function () {return 
   this.element.css ({ 
    Color: ' Red ' 
   }); 
  }; 
 

The @element in the code points to a jquery object that is specified elsewhere-such as Object.element = $ (' #some_div ').

Any callback function specified using "=>" is automatically bound to the original object, yes, that's cool.

In the 2011 the function is called like this

Have a look at this:

$.post ( 
 "/posts/update_title" 
 new_title:input.val () 
 id:something 
 -> alert (' Done ') 
 ' JSON ' 
) 

With Coffeescript, multiple arguments can be written as multiple lines, and commas and braces are optional, making it easier to read some of the more lengthy methods of signing in jquery such as $.post () and $.animate (). Here's another example:

$ (' #thing '). Animate 
 Width: ' +20px ' 
 opacity: ' 0.5 ' 
 easeoutquad ' 

It's a delicious coffee, isn't it? Note that the first parameter is an anonymous object, and you can even omit the parentheses of the calling function.

Make the initialization more sexy.

When I first started using jquery, I did this. Page initialization:

$ (document). Ready (function () { 
 some (); 
 Init (); 
 Calls (); 
}) 

Coffeescript and the new version of jquery make the above code evolve so sexy:

$-> 
 Some () 
 init () 
 calls () 

The function definition syntax is already very cool in Coffeescript itself, and can be used on these occasions to make it cooler. You will find that all function calls that require callbacks are so simple in coffeescript.

In fact, Coffeescript is a very flexible language because it can be translated into JavaScript in a one-to-one manner. There are more than one way to bring it into the project. Here, I will first introduce the node project Coffeescript Way to make a summary, and compare the pros and cons of each way.

Run a pure Coffeescript project directly using the Coffee command

General mention Coffeescript, naturally will think he is JavaScript's younger brother, always out of JS shadow. You can actually think of it as a separate language. We all know that on the node platform after the global installation of the Coffee-script package, you can go through the coffee instructions into the Coffeescript interface, call it REPL also line. If your project is written entirely with coffee, it's easy, just use the coffee command for your entry script, such as "App.coffee", and then execute:

Coffee App.coffee

Note that the extension coffee here cannot be omitted.

This approach should be said to be the most "official" way to use Coffeescript. Simple, Direct! Moreover, once you use a coffee file as the entry point for the project, the entire project is compatible with both coffee and JS. You can arbitrarily require JS or coffee files and modules in the project, and can even require coffee files in the JS files in the project. And when you refer to either coffee or JS files, you do not need to extend the name, as long as the previous part of the name does not conflict.

One of the biggest problems with this approach is that if it acts as a module, it can only be used for coffee projects; If he is an application, the running environment must be installed Coffee-script. After all, Coffeescript is still a small language, it as a module when the loss of JS users is really a pity.

Another possible disadvantage is performance, after all, node inside only JS engine, coffee code needs to compile for JS before running, this process is to consume a little time, although coffee to JS compiler speed is actually very fast. However, this should not be a big problem, in general, require are written in the top of the file, that is, the application in the start-up when the require of the files are require, require when the coffee was compiled into JS into the JS engine, So the time that the compilation consumes is concentrated in the application starts, the runtime hardly encounters the require new coffee situation. The most common use scenario for node is the Web server, which is even more problematic.

Referencing Coffeescript in a JavaScript project

Coffee-script in NPM can be installed either globally or as a module of the project. What's the point of Coffee-script as a module of the project? In fact, you add a coffeescript compiler to your project, and the project can compile coffee files at run time.

You must want to refer to coffee files as casually as in the first way. No problem, just register. If your project entry file is App.js, then just add this to the front of the file:

Require (' coffee-script/register ');

Then you can require coffee files in the project.

This approach is essentially the same as the first way, except that Coffee-script is not installed in the global, so your module can be independent, as the application does not need the environment to install good coffee-script.

Shortcomings, I think the biggest problem is easy to make code a bit messy, a while JS, a while coffee, of course, the first way may also be so, but all with coffee started inside should not write JS it ... In a word, I think a project or the language unified better (unfortunately I mainly in this way, in a JS has been written in the general structure of the project, I would like to use coffee swollen mody do ... )

The performance problem is the same as the first way, not much.

The Orthodox way--compiling

Once the compilation, I feel back to the serious of the C or Java era. Indeed, as a compiled language, compiling and then running is the right path. c There are Gcc,java Javac,cofee have coffee-c.

It is easy to compile a cofee file, such as to edit the App.coffee file, which is executed in the current directory of the file:

Coffee-c App.coffee

A file named App.js appears in the current directory. This instruction can also be applied to the directory, such as you put all the coffee source files in the project in the SRC directory, then execute:

Coffee-c SRC

All coffee source files in the SRC directory and its various subdirectories are compiled into a JS file and placed in the same directory as the source file.

However, for large projects, it is not good to put the source file and the compiled result file together. It's OK to specify an output directory:

COFFEE-C-o outputs src

The parameter order of this instruction is a bit strange. This is defined in the help of coffee:

coffee [Options] path/to/script.coffee--[args]

Note that all options are between the coffee and the file path. The final args is the parameter to pass when the target file is executed as a script. That means that all the options are placed between the coffee and the filename. And-c This option is separate, does not have its own parameters, it only means that the instructions to the last side of the file provided to compile, so write this is also the line:

Coffee-o outputs-c src

If you want to add an option so that the result of the compilation is not surrounded by the execution function body, it is:

Coffee-o Outputs-c-B src

If you want to compile all the source files into a target file named Out.js, you are:

Coffee-o outputs-c-j out SRC

It's annoying to execute instructions every time a pity Dorado code. Coffee directive has an option-----------------

Coffee-o outputs-c-W SRC

For large projects, it's best to make sure that the compilation is done in advance, so that all developers need only one instruction to fix all the things that are compiled, and this needs to be built automatically.

Offee provides an automated build tool, cake, just like make in C world. But as the official web site says, cake is a very simple build system. In fact, the function of cake is to execute a script called Cakefile, and the Cakefile script is written in Coffeescript. This script provides only a very limited set of built-in functions, such as a task, to declare a command and its corresponding description and execution function. The other is to write a pure node project, want to compile either use node's FS module output coffee module compiled strings, or use child_process module to execute shell directives. In fact, the goal of cake construction does not have to be coffee, because it actually executes a node script that handles anything that is automated.

There are also a number of better third-party automation building tools can also be completed coffee automatic compilation, such as the famous grunt, as well as the domestic fekit.

This orthodox way of compiling may seem the most reliable, and should be loved by older programmers. It allows the team to form a fixed development model. In addition, the compiled project becomes a pure JS project, whether as an application directly or as a module by other project references do not need additional dependency. And there is no need for compilation at run time, and there is no performance problem with compilation at all.

The disadvantage is that it is too troublesome. If you are going to do a not too big project, Cakefile or configure Grunt to spend half a day, not very worthwhile.

Through the introduction of the use of Coffeescript in Jquery,node.js,javascript, do the small partners have a new understanding of coffeescript?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.