Mathieu
Mathieu

Reputation: 4787

Rails 4 - Moving js inline script inside View to JS file

I would like to move some js inline scripts I have on my homepage to a javascript file (in Assets) but there is some complexity due to variables.

home.html.erb

<div>
this is the homepage
</div>
<script>
  <% @deal.deal_details.each_with_index do |popin, index| %>
  <% index_plus_one = index + 1 %> 
    function loadInfoPopin() {
      var msg;
      msg = Messenger().post({
        message:  '<%= j render partial: "deals/info_popin/info_popin#{ popin['popin_id'] }",
                  locals: { popin: popin, index: index_plus_one } %>'
      });
    } 
  <% end %>
</script>

For the sake of information here is the format of the Deal's column/attribute 'deal_details' (it's a json attribute):

[{"popin_id":"4","text1":"qqq","text2":"sqsq","image1":"sqqs"},{"popin_id":"5","text1":"sqqs","video1":"s"}] 

This is an example and you can have as many json block inside the array as possible.

deals/info_popin/info_popin5.html.erb (it's an example)

<div>
       <p><a href="<%= popin['image1'] %>">cool image</a></p>
    </div>
</div> 

Now, how can I move the whole script or at least the function loadInfoPopin() to a javascript file (that is to say away from the view home.html.erb) ?

Thanks

Upvotes: 1

Views: 262

Answers (2)

Andrew
Andrew

Reputation: 1787

How about moving the loadInfoPopin() function into a separate JS file and altering the function slightly to take in an argument for the html message?

function loadInfoPopin(html_message) {
  Messenger().post({
    message:  html_message
  });

Setup the html for the message within the loop before passing into and calling loadInfoPopin.

Upvotes: 1

Andrievs Niedra
Andrievs Niedra

Reputation: 26

.js.erb is an option. This way the js files will be parsed before compiling. Not sure though it will work the way you want.

I would recommend to leave the variables in the layout as vars and moving only the static JS parts to the assets.

Upvotes: 0

Related Questions