在连接后将所有CoffeeScript文件包装在JQuery文档就绪函数中?

时间:2013-03-18 20:09:29

标签: jquery coffeescript concatenation

我有许多CoffeeScript文件,在转换为Javascript之前,我使用Cakefile连接这些文件。如何在文档就绪函数中使用JQuery包装连接的CoffeScript文件?

例如:

我有以下CoffeScript文件,每个文件都包含一个类:

foo.coffee bar.coffee tea.coffee

为了生成JS文件,我使用以下Cake命令来连接咖啡并生成JS:

task 'build', 'Build single application file from source files', ->
  appContents = new Array remaining = appFiles.length
  for file, index in appFiles then do (file, index) ->
    fs.readFile "#{file}.coffee", 'utf8', (err, fileContents) ->
      throw err if err
      appContents[index] = fileContents
      process() if --remaining is 0
  process = ->
    fs.writeFile '../assets/js/app.coffee', appContents.join('\n\n'), 'utf8', (err) ->
      throw err if err
      exec 'coffee --compile ../assets/js/app.coffee', (err, stdout, stderr) ->
        throw err if err
        console.log stdout + stderr
        fs.unlink '../assets/js/app.coffee', (err) ->
          throw err if err
          console.log 'Done.'

这样就产生了我很好的JS文件:

// Generated by CoffeeScript 1.3.3
(function() {

   ...all the code...

}).call(this);

我该怎么做才能将所有代码包装在一个JQuery on ready函数中,如下所示:

(function() {

    $(document).ready(function() {
       ...all the code...
    });

}).call(this);

因此,基本上希望在文档准备好之后执行所有连接的代码。

子问题我问的是正确的方法吗?我应该将每个CoffeeScript文件中包含的每个类包装在一个on document ready函数中吗?

非常感谢任何帮助,我已经搜索了如何以及低的答案,但没有用。

谢谢!

2 个答案:

答案 0 :(得分:1)

这里的第一个决定是你是否使用coffeescript的isoliation模式。这封装了每个coffeescript文件的所有代码。您可能需要公开一些代码,例如:

foo.coffee

class Foo
  a: 20
  f: () -> 
      console.log("...")

window.Foo = Foo

之后,您可以在每个文档中使用公开的代码部分,例如:

$(document).ready(function() {
   var f = new window.Foo();
});

答案 1 :(得分:1)

首先,CoffeeScript编译器已经有join命令:

-j, --join [FILE]  
     

在编译之前,按照传递的顺序将所有脚本连接在一起,并且      将它们写入指定的文件。用于构建大型项目。

其次,您可以直接将此功能直接传递给$(document).ready(function () { ...} ) - $()

,而不是使用$(function () { ... });

对于您的实际问题,有几种方法可以做到。

选项1:

使用-b / --bare选项编译.coffee文件,然后手动连接包含$(function() {的文件和最后的开头});(但这非常粗略)。

选项2:

使用exports = window ? this之类的东西来获取全局对象,并将您希望在jQuery加载函数中运行的功能分配给该全局对象,例如:

FooModule = do ->
  class Foo 
    constructor: (@blah) ->

  init = ->
    blah = new Foo('bar')

  init: init

exports = window ? this
exports.Foo = FooModule

然后,您可以拥有另一个包含以下内容的文件:

$(->
  Foo.init()
)

希望其中一个选项好吗?