问题描述
我正在开发一个业余应用程序并使用一些jQuery.目前,结果还不错,但是我是jQuery noob,我认为我可以对代码结构进行一些重大改进.暂时不考虑Coffescript,我一直想知道的一件事是如何在资产管道中正确使用特定于模型的.js
文件.
I'm working on a hobby app and using some jQuery. The results are fine at the moment, but I'm a jQuery noob and I assume that there are some significant improvements that I can make to the code structure. Putting aside Coffescript for the moment, one thing that I've been wondering is how to properly use the model-specific .js
files in the asset pipeline.
例如,当使用我的用户模型时,当文档准备好时,我可能想要运行一些代码.假设我将其放在Rails 3.1生成的users.js
文件的$(document).ready(function() {...});
中.
For example, when working with my User model, I may have some code that I want to have run when the document is ready. Let's say I put that in $(document).ready(function() {...});
in the users.js
file generated by Rails 3.1.
第二天,我正在使用Pet模型,并且已经准备好要与文档一起运行的代码.我把它放在Rails准备的pets.js
文件中的另一个$(document).ready(function() {...});
中.
The next day, I'm working with the Pet model and I have code that I want to run with the document is ready. I put that in another $(document).ready(function() {...});
inside of the pets.js
file that Rails prepares.
在这里出现我的问题:
- 应用运行时如何编译?
- 我是否使用上面的示例实例化了两个jQuery实例?
- 我应该只在应用程序中使用一次
$(document).ready(function() {...});
还是Rails会将我的代码编译到一个调用中? - 特定于模型的
.js
文件属于什么? - 在开发和生产模式下执行方式之间是否有区别?
- How does that compile when the app runs?
- Am I instantiating two jQuery instances with the example above?
- Should I only use
$(document).ready(function() {...});
once in the app or does Rails compile my code into a single call? - What belongs in the model-specific
.js
files? - Are there differences between how it will execute in development and production modes?
推荐答案
1)编译:Rails资产管道仅将所有javascript文件合并为一个大文件.
1) Compilation: Rails assets pipeline just combines all javascript files in one big file.
2)jQuery仅加载一次,您具有多个$(document).ready
函数,但这不是问题
2) jquery is only loaded once, you are having multiple $(document).ready
functions, but that is not a problem
3)Rails对该调用不执行任何操作,并且jQuery可以安全地处理每页更多的这些块.
3) Rails does not do anything with the call, and jQuery can safely handle more of those blocks per page.
4)您将其称为特定于模型的.js
,我宁愿将其称为特定于控制器.您将属于一起的功能分组在一起.将它们联系在一起的是控制器还是模型并不重要.我们将js分成单独的文件,以使其更易于管理.
4) You call it a model-specific .js
, I would rather call it controller-specific. You group functionality together that belongs together. Whether the thing that ties them together is a controller or a model really does not matter. We split our js up in separate files to make it more manageable.
5)在开发中,资产是根据每个请求进行编译的,而在生产中,资产只能进行一次.在生产中也可以将其缩小和压缩.
5) In development the assets are compiled on every request, in production it is done only once. Also in production it could be minified and compressed.
希望这会有所帮助.
这篇关于如何在Rails 3.1资产管道中正确使用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!