Ruby on Rails with Unobtrusive JavaScript - URL Management

I use a modular system of JavaScript files when working in Rails - basically, each view will have its own module in the .js file. My problem arises when I need a dynamic Rails string generated in my JavaScript, such as translation strings and URLs.

Translations work fine with babilu , but I still stick to the URL generation. I could write something that looked at the routes in the application and generate JavaScript methods that I could pass as object identifiers.

An alternative would be to pass the already generated URL to any functions that I called, which sounds messy, but may be the most flexible alternative.

+3
source share
3 answers

I don’t know that there is a really nice way to do this, but one possibility is for your server code to write a small block <script>on the page to declare some variables that your packaged Javascript can detect and use.

<script>
  var pageGlobals = {
    interestingURL: <% ... url %>,
    ...
  };
</script>

I did this to keep track of things like sub-directories of images that are defined by a child of a client. Javascript code just knows that whenever it is needed for a URL, it can just go to the global object and select a standardized variable.

, , Javascript, <script> - . , .

+3

, . HTML 5 .

:

<button id="myButton" data-url="<%= my_resource_path %>">Click me</button>

js:

var myurl = $("#myButton").data("url");

. .

+3

. javascript. , .js :

var users_path = '<%= users_path %>';

, .js (, , rails html).

, . , , ,

<%= select_tag :select_something, select_options, 'data-url' => users_url %>

javascript. , .

Edit: Well, actually, someone implemented the idea of ​​a dynamic .js file. It seems straightforward enough, just create a javascripts controller and bind its actions via javascript_include_tag: dynamic javascript files

0
source

Source: https://habr.com/ru/post/1757656/


All Articles