Dglgmut
Dglgmut

Reputation: 45

Is there a better way to do Unobtrusive JavaScript on Ruby on Rails?

The way I found to put javascript on a separated file without the use of RJS or ERB was using an instance variable at javascript_include_tag helper.

<%= javascript_include_tag @extra_head_content if !@extra_head_content.nil? %>

Then I put the name of the current javascript file at the instance variable from the controller;

def index
    @extra_head_content = "test"
#...
end

And at my javascript file (test.js) I add some code.

 $j(function() {
  alert("test");
 })

Is there any "better" way to do this? Any convention that I'm missing?

I found a lot of information for UJS to XHR(AJAX) but nothing abot the conventions for a simple thing like " unobtrusive (document).ready"

I'm using rails 3-0-9.

Upvotes: 1

Views: 138

Answers (2)

Michael Fairley
Michael Fairley

Reputation: 13208

I do something like this:

in ApplicationHelper:

def javascript(file)
  content_for(:javascript_at_head){ javascript_include_tag file }
end

in layouts/application.html.erb

<%= yield(:javascript_at_head) %>

and in another template:

<% javascript :test %>

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160191

Why not use content_for and yield?

Upvotes: 1

Related Questions