views:

108

answers:

4

I have a javascript part in my view, that I want to modify through locals I have defined in a helper.

<script type="text/javascript">
var store = new Ext.data.JsonStore({
 url: '/admin/administration/users/grid_data.json',
 root: 'users',
    fields: [
 <%- for field in fields do -%>
       {name: '<%= field[:data_index] -%>'},
 <%- end -%>
    ]
});
</script>

This doesn't work, can you help me?

+1  A: 

The problem is that you are going to have a trailing comma. You need to check the lenght of your field array and if it is the last element simply do not include the comma you currently have at the end of every name parameter.

wgpubs
A: 

First thing is to look at the generated code from the page source. Any syntax errors there? Is Ext library included somewhere in the head section of the HTML?

Mohsin Hijazee
A: 

What about:

<%= (fields.collect {|field| "{name: #{field[:data_index]}}"}).join(',') %>
Reuben Mallaby
+3  A: 

Hi Oxymoron,

This script won't work in IE becuase of it's strict Javascript parser. The for loop in your code leaves a trailing , at the end of the array. That's not a valid Javascript syntax. The easiest way to move data from ruby into javascript is almost always to_json:

<% javascript_tag do %>
var store = new Ext.data.JsonStore({
    url: '/admin/administration/users/grid_data.json',
    root: 'users',
    fields: <%= fields.collect{|f| { :name => f[:data_index] } }.to_json %>
});
<% end %>

And you can leave out the .collect{|f| { :name => f[:data_index] } } if you use the same hash key in Ruby and Javascript. Much nicer, and much less prone to bugs.

Good luck!

mixonic