开发者

How do you organize javascript files in Rails 3?

I'm writing a web app in Rails 3 and I'm using JQuery as my Javascript framework. I don't have a ton of javascript in the application yet but I'm beginning to add transitions between pages and I'm wondering if there's a good way to use [function].js.erb files to organize the transitions. For example, I have an invitations controller with a new and edit function. Is there a way to use views/invitations/new.js.erb and views/invitations/edit.js.erb to run a function when the document is ready? Right now I'm just using these to handle page 开发者_如何学编程manipulation after an AJAX call.

Thanks!


I agree with apneadiving.. personally, the js.erb calls add alot of cognitive overhead. What I do is load my javvavscripts into a layout partial

*app/views/layouts/_javascripts.html.haml

= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js'
= javascript_include_tag "http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js" 
= include_javascripts :app
= hoptoad_javascript_notifier
= yield :javascripts

Then I use the jammit command from the Jammit gem to minifiy, and compress my js and css assets

config/assets.yml

javascripts:
  app:
    - public/javascripts/rail.js
    - public/javascripts/underscore-min.js
    - public/javascripts/jquery.dump.js
    - public/javascrippts/etc*.js

The for each page needed custom page-level js, I throw a content_for :javascripts block in at the bottom of the page:

app/views/something/awesome.html.haml

%h1 cool page
Other cool stuff

- content_for :javascripts do
  :javascript
    $(document).ready(function(){
      console.log('This document is REaDY!! and, this page rocks');
      $.ajax({
         url: "#{new_item_path(@item)}",   //ruby is evaluated due to string interpolation
         success: function(data) {
           console.log('Loaded ' + data + ' from ' + #{new_item_path(@item)})
         } 
      });
    };

This lets me then to a render 'layouts/javascripts' at the bottom of my application.html.haml layout, and all of my javascript geets piped to the bottom of the page, so speed up page load as suggested here by Yahoo This also lets me use the erb to generate variables for the page-level js from Rails if needed


The js.erb files are just meant for the prior usage you had: ajax or js calls.

I wouldn't recommend it though: this should remain client-side IMHO. Plus it will be moved apart Rails in 3.1 (still kept as a gem).

You should simply put your js in files you load in your views: basic & neat.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜