Home  >  Article  >  Web Front-end  >  Summary of ways to use coffeescript_javascript skills

Summary of ways to use coffeescript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:47:06962browse

As the low-key younger brother of Javascript, Coffeescript is really outstanding. Using it can improve development efficiency, reduce code errors, and the key is to greatly enhance the pleasure of development. More and more, I feel that I should use coffee in my projects whenever possible.

However, maybe you are like me. After understanding the syntax of coffeescript and preparing to try it out, you are worried about how to introduce it into the project.

Command your code like a boss

CoffeeScript provides a bunch of cool array iteration methods. The best thing is that this not only works with arrays, but also with jQuery objects. Let’s write poetic code:

formValues = (elem.value for elem in $('.input')) 

This line of code will be translated into the following Javascript:

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, writing code like this is really scary at first, but once you start embracing the magic of CoffeeScript, you will fall in love with it.

Binding using normal methods

Using "="" in jQuery's callback will greatly save you the trouble of manually binding methods to objects. Let’s take a look at some code:

object = 
 func: -> $('#div').click => @element.css color: 'red' 

The following is the compiled Javascript 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' 
   }); 
  }, this)); 
 } 
}; 

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 "=>" will be automatically bound to the original object, and yes, that's cool.

This is how the function was called in 2011

Take a look at this:

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

Using CoffeeScript, multiple parameters can be written in multiple lines to call. Commas and braces are optional, which makes some methods with longer signatures in jQuery such as $.post() and $.animate() easier to read. Here’s another example:

$('#thing').animate 
 width: '+20px' 
 opacity: '0.5' 
 2000 
 'easeOutQuad' 

Delicious coffee, isn’t it? Note that the first parameter is an anonymous object, you can even omit the meta brackets in the function call.

Make initialization sexier

When I first started using jQuery I initialized the page like this:

$(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 in CoffeeScript is already very cool, and being able to use it in these situations makes it even cooler. You will find that all function calls that require callbacks are so simple in CoffeeScript.

In fact, coffeescript is a language that is very flexible to use because it can be translated into JavaScript one-to-one. There is also more than one way to introduce it into a project. Here, I will first summarize the ways to introduce coffeescript into node projects and compare the advantages and disadvantages of each method.

Directly use the coffee command to run pure coffeescript projects

Generally speaking, when coffeescript is mentioned, one will naturally think of it as the younger brother of javascript, which can never escape the shadow of js. In fact, you can think of it as an independent language. We all know that after installing the coffee-script package globally on the node platform, you can enter the coffeescript interactive interface through the coffee command. You can also call it repl. If your project is completely written in coffee, it is simple. Just use the coffee command directly on your entry script. For example, if your entry script is named "app.coffee", then execute:

coffee app.coffee

注意,这里的扩展名coffee是不能省略的。

这个方式应该说是使用coffeescript最“官方”的方式。简单,直接!而且,一旦你以一个coffee文件作为项目的入口, 那整个项目就同时兼容coffee和js了。你在项目里可以任意require js或coffee文件及模块, 甚至可以在项目中的js文件中随便require coffee文件。并且在你引用无论是coffee还是js文件的时候都无需扩展名, 只要前面部分名称不冲突就行。

这个方式有个最大的问题就是,如果它作为一个模块,只能被用于coffee项目;如果他作为一个应用, 运行环境必须安装coffee-script。毕竟coffeescript现在还是一个小众语言,它作为模块时丧失了js用户实在可惜。

另一个也许存在的缺点是性能方面的,毕竟node里面只有js引擎,coffee代码需要先编译为js再运行, 这个过程是要消耗一点点时间的,尽管coffee到js的编译速度其实挺快的。不过这应该不是什么大问题, 一般来说,require都是写在文件的顶部,也就是应用在启动的时候就一气儿把该require的文件都require了, require的时候coffee就被编译成了js放到了js引擎中,那么编译消耗的那点时间都集中在了应用启动时, 运行时几乎不会遇到require新的coffee的情况了。node最常见的使用场景是web服务器,这就更没问题了。

在javascript项目中引用coffeescript

npm中的coffee-script既可以全局安装,也可以作为项目的一个模块安装。那coffee-script作为项目的一个模块有啥意义呢? 其实是给项目添加了一个coffeescript的编译器,这个项目就可以在运行时随时编译coffee文件。

你一定希望像第一种方式里那样随便引用coffee文件。没问题,只需要注册一下。假如你的项目入口文件是app.js, 那么只需要在这个文件最前面加上这么一句:

require('coffee-script/register');

然后你就可以在项目中随便require coffee文件了。

这个方式本质上和第一种方式没啥区别,只不过coffee-script没安装在全局,因此你的模块可以独立存在, 作为应用也不需要环境安装好coffee-script了。

缺点嘛,我觉得最大的问题就是容易让代码有些乱,一会儿js,一会儿coffee,当然第一种方式也可能会这样, 不过都用coffee启动了里面应该不会写js了吧……总之我觉得一个项目还是把语言统一起来比较好 (遗憾的是我主要用这种方式,在一个已经用js写出了大体结构的项目里,我就想用coffee肿么办……)

性能问题上跟第一种方式一样,不多说了。

正统的方式——编译

一说编译,就感觉回到了正儿八经的C或Java的时代。的确,作为一个编译型语言,编译后再运行才是正道。 c有gcc,java有javac,cofee有coffee -c。

要编译一个cofee文件很简单,比如要编辑app.coffee这个文件,就在文件的当前目录执行:

coffee -c app.coffee

一个名为app.js的文件就出现在当前目录下了。这个指令也可以应用于目录, 比如你把项目中所有的coffee源文件放到了src目录下,那就执行:

coffee -c src

src目录及其各级子目录下的所有coffee源文件都会编译成js文件,放到和源文件相同的目录中。

不过对于大型项目,把源文件和编译结果文件放到一起可不太好。指定一个输出目录就行了:

coffee -c -o outputs src

这个指令的参数顺序有点奇怪。在coffee的帮助里是这么定义的:

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

注意,所有的选项(options)都在coffee和文件路径之间。而最后的args是把目标文件作为脚本执行时给传递的参数。 也就是说所有的选项都放在coffee和文件名之间就可以了。 而-c这个选项是单独的,没有自己的参数,它只表示要把指令最后面提供的那个文件给编译了,所以写成这样也行:

coffee -o outputs -c src

假如想再加个选项,让编译结果不被自执行函数体包围,就是:

coffee -o outputs -c -b src

再假如想把所有源文件编译成一个名为out.js的目标文件,就是:

coffee -o outputs -c -j out src

如果每次改点代码都要这么执行指令也挺烦人的。coffee指令有一个选项-w可以监视源文件的变动而自动编译:

coffee -o outputs -c -w src

For large-scale projects, it is best to determine the compilation method in advance so that all developers can complete all compilation matters with only one instruction. This requires automated construction.

offee provides an automated build tool, cake, which is like make in the c world. But as stated on the official website, cake is a very simple build system. In fact, the function of cake is to execute a script named cakefile, and the cakefile script is written in coffeescript. This script only provides very limited built-in functions, such as task, which are used to declare an instruction and its corresponding description and execution functions. The other thing is to write a pure node project. To complete the compilation, you must either use the fs module of node to output the string compiled by the coffee module, or use the child_process module to execute shell instructions. In fact, the target of cake construction does not necessarily have to be coffee, because it actually executes a node script and can handle any automated things.

In addition, there are some better third-party automated construction tools that can also complete the automatic compilation of coffee, such as the famous Grunt, and the domestic fekit, etc.

This orthodox compilation method may be the most reliable and should be loved by experienced programmers. It allows the team to form a fixed development model. In addition, the compiled project becomes a pure js project, and no additional dependencies are required whether it is run directly as an application or referenced by other projects as a module. And there is no need to compile at runtime, so there is no performance problem caused by compilation.

The disadvantage is that it is too troublesome. If you are doing a small project, it will take half a day just to create the cakefile or configure grunt, which is not worth it.

Through the introduction of coffeescript in jQuery, node.js, and javascript, have you gained a new understanding of coffeescript?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn