Reputation: 632
UPDATE 2:
I have temporarily fixed my problem by moving the javascript directly into my view file, but I would still like to know why Rails isn't reloading my javascript files when I move between pages using <a>
tags.
UPDATE 1:
I tried splitting the code into 2 views, one for the languages and one for the text changes. When I link to the text page using an Anchor from the language page, even if I didn't do anything else on the language page beforehand, the contents of my home.js file doesn't run again. Something is happening to destroy and create views without running the document.ready
javascript again.
ORIGINAL: I am trying to build a Rails App that has multiple language support, but it's breaking the javascript farther down the page. In my view I have 2 anchors to switch between English and French, which when clicked refresh the page and all the text, language supported or not. This is expected.
After I click on either of these links however, the keyup
javascript event i defined for a textarea farther down the page breaks entirely. I am not getting any errors in the Rails or javascript console, it just stops working.
What is even more confusing is that while the code works before I click the anchors I am changing the text in the textarea from it's default value on page load. After I click the anchor the text changes back to the default page text as expected and my javascript breaks. If I refresh the page with F5
after it breaks, not only does the javascript work and the new language setting save, but the oldest value from the time the textarea javascript was still working reappears.
Example sequence of events:
home.html
<h3><%= t('intro-title') %></h3>
<p><%= t('intro-paragraph') %></p>
<a href="/?locale=en" type="button">English</a>
<a href="/?locale=fr" type="button">Français</a>
<textarea id="l33tify-in">Try it out!</textarea>
<textarea id="l33tify-out" disabled="true">72y 17 0u7!</textarea>
home.js
$( document ).ready(function() {
$('#l33tify-in').keyup(function(){
$.get('/l33tify_text', { 'l33tify_me' : $(this).val() }, function(data) {
$('#l33tify-out').val(data['l33tified']);
});
});
});
home_controller.rb
class HomeController < ApplicationController
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def index
end
end
Upvotes: 1
Views: 1487