1

In my rails app I would like to perform a certain block of JS when in my 'events' controller, and another block while in my 'movie_interests' controller.

I am aware that this condition can be checked using 'params[:controller] == ...', but this is ruby code. How can I accomplish this from a javascript file?

$(".search-results").on('click', ".movie-click", function(){
    if (params[:controller] == "events") {    //This is incorrect syntax, but shows more or less what I want to accomplish
      $('#event_rt_id').val($(this).data("id"));
      $('#movie-poster').html('<img id="selected-poster" src="' +               $(this).data("poster") + '" />' );
    }
});
1
  • Stack Snippets are for code that could be run here on the site, with complete HTML and such. For just code blocks, use the code block button. (Confusing, I know.) Commented Dec 13, 2014 at 18:22

2 Answers 2

1

One possible solution is to include a unique HTML element on each page. For example on pages rendered by the EventsController, you could include a <div class="events">. Then your JavaScript code can just check the presence of these elements.

Another option would be to include the controller name, for example in the body element. You can do this in your layout:

<body data-controller="<%= controller_name %>">

You can then use the controller name in the JavaScript.

I would prefer the first solution though.

Sign up to request clarification or add additional context in comments.

Comments

0

In you application.html.erb, add the following code

<script type="text/javascript">
    window.controller = "<%=params[:controller] %>"
</script>

So in your javascript, you can access the variable controller, which tells you which controller you are in.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.