Improve unobtrusive javascript (and possibly use CoffeeScript) in a Rails application?

There are some solutions like js-routes (my fork) which will allow you to write Router. Post_path(3) in your JS/CS. This way you can get around hardcoding urls.

Routes There are some solutions like js-routes (my fork) which will allow you to write Router. Post_path(3) in your JS/CS. This way you can get around hardcoding urls.

Mixing JS and ERB I would advise you to avoid mixing JS and Ruby. In most cases you can get around that by refactoring your JS code, the result will be easier to read and can simply be moved into a pure JS/CS-file. # based on your vote-link example and assuming that your link # looks like: # # %a(href="#"){:"data-company-id" => @company.Id} Vote # => Vote makeAllCompaniesVotable: () -> $('.

Company a. VoteLink'). Click -> companyId = $(this).

Data('company-id') $. Ajax url: Router. Vote_company_path(companyId) # ... Unless you do evil eval-magic, you won't even need escape_javascript.

But you will have to remove the JavaScript from inside your partials. Jquery. Livequery made the transition easier.

$(`. Company`). Livequery -> # do something with $(this) will be called each time a .

Company is inserted into the document. Hardcoding DOM-Paths If you are writing code for a specific dom-tree (or a specifc view) I wouldn't consider it a bad practice. Writing unobtrusive JS is like writing CSS - and we hardcode #company_list_container in CSS too, don't we?

$("#vote_link_") # this is ugly though Calling the JS code from the frontend To have an interface between the static CoffeeScript-files and the views I tend to write something like: :javascript $(function(){Companies.index()}); $(function(){Application. GlobalEnhancements()}); at the end of my views. This will then call a function I wrote with CoffeeScript, which will then enhance the site with all the needed scripts.

There might be better approaches (like having a Rails-like Router for JavaScript - see Backbone. Js) but it's simple and works for me. Also if I need some data quite often (for example: the current_user): :javascript window.

Current_user = #{current_user. To_json}; However I don't think there is an efficient way to refactor. I had to do a lot of refactoring to get my ERB/JS mess removed.

Still worth, though.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions