在连接后将所有CoffeScript文件包装在JQuery文档就绪函数中?
我有许多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函数中?
非常感谢任何帮助,我已经搜索了如何和低的答案,但无济于事。
谢谢!
这里的第一个决定是你是否使用coffeescript的isoliation模式。 这封装了每个coffeescript文件的所有代码。 您可能需要在里面公开一些代码,例如:
foo.coffee
class Foo a: 20 f: () -> console.log("...") window.Foo = Foo
之后,您可以在每个文档中使用公开的代码部分,例如:
$(document).ready(function() { var f = new window.Foo(); });
首先,CoffeeScript编译器已经有一个join
命令:
-j, --join [FILE]
在编译之前,按照传递顺序将所有脚本连接在一起,并将它们写入指定的文件。 用于构建大型项目。
其次,不要使用$(document).ready(function () { ...} )
,而只需将函数直接传递给$()
– $(function () { ... });
对于您的实际问题,有几种方法可以做到。
选项1:
使用-b / --bare
选项编译.coffee文件,然后手动连接包含$(function() {
和start和});
最后(但这非常重要)。
选项2:
使用像exports = window ? this
这样的东西exports = window ? this
exports = window ? this
为了获取全局对象,并将您希望在jQuery加载函数中运行的function分配给该全局对象,例如:
FooModule = do -> class Foo constructor: (@blah) -> init = -> blah = new Foo('bar') init: init exports = window ? this exports.Foo = FooModule
然后,您可以拥有另一个包含以下内容的文件:
$(-> Foo.init() )
希望其中一个选项好吗?