Geo
Geo

Reputation: 96827

How do you mix JS and Ruby code in a view for later JS usage?

I am using a jquery UI DatePicker widget to show a calendar. Each day in the calendar is represented by a collection of Result object, which belong to an Objective model. If all the results for a day are succesful, I'm setting a class on the calendar cell, to make it green. If at least one of them failed, I'm making it red. If no results exists, I'm making it grey. Right now , I do something like this:

<%= start_day .. end_day do |day| %>
   <div class="hidethis" id="<%= [day.year,day.month,day.year].join(",") %>" value="<%= objective.result_status_for_day(day)%>"/>
<% end %>

I am storing data in hidden divs, and later, when I'm initializing the calendar, in the beforeShowDay I'm going through the div ids to find the one relevant to me, and I set the class responsible for colouring the cell. Is there another way of doing this, or is this something which other people use in practice?

Upvotes: 1

Views: 1390

Answers (2)

mu is too short
mu is too short

Reputation: 434665

Using HTML for data storage seems a bit round-about. Why not store your data as JavaScript data? Something like this:

<script type="text/javascript">
    window.app = window.app || { };
    window.app.objective_data = <%= @raw_objective_data.to_json.html_safe %>;
</script>

Then set up your raw data in Ruby, leave it in @raw_objective_data, and then load it into your client-side models during your initialization pass. Or you could load the data straight into your (Java|Coffee)Script through a simple AJAX call.

You'll also want to avoid '</script>' and similar things in @raw_objective_data.to_json, you can learn about that over here.

Upvotes: 2

osahyoun
osahyoun

Reputation: 5231

I wouldn't use the id and value attributes. I don't think the div tag even supports the value attribute. Instead I'd use data attributes, which allow you to write valid HTML markup while simultaneously embedding data within your page.

<%= start_day .. end_day do |day| %>
   <div class="hidethis" data-date="<%= [day.year,day.month,day.year].join(",") %>" data-value="<%= objective.result_status_for_day(day)%>"></div>
<% end %>

var value = $('div').attr('data-value');

Upvotes: 1

Related Questions