I.Manev
I.Manev

Reputation: 727

jquery.i18n in C# MVC

I'm using the jquery.i18n library for the translations in my application. The problem is that everything works as expected, except if I go from one view to another - the locale is lost and set with the default value. I'm using also jquery.history.js and url.min.js :

var set_locale_to = function(locale) {
    if (locale) {
      $.i18n().locale = locale;
    }
    $('body').i18n();      
};

jQuery(function() {
  $.i18n().load( {
    'en': '../js/i18n/en.json',
    'ru': '../js/i18n/ru.json',
    'dk': '../js/i18n/dk.json'
  } ).done(function() {
      set_locale_to(url('?locale'));

      History.Adapter.bind(window, 'statechange', function(){
        set_locale_to(url('?locale'));
      });

      $('.switch-locale').on('click', 'a', function(e) {
        e.preventDefault();
        History.pushState(null, null, "?locale=" + $(this).data('locale'));
      });
  });

});

Is there something that I am missing or doing wrong? I also tried to set the window to a fixed string, but this didn't work either.

Upvotes: 1

Views: 370

Answers (1)

I.Manev
I.Manev

Reputation: 727

So far I managed to solve my problem, using window.localStorage:

var set_locale_to = function(locale) {
  if (locale) {
      $.i18n().locale = locale;
    }
    $('body').i18n();
};

jQuery(function() {
  $.i18n().load( {
    'en': '../js/i18n/en.json',
    'ru': '../js/i18n/ru.json',
    'dk': '../js/i18n/dk.json'
  } ).done(function() {
    set_locale_to(url('?locale'));

    History.Adapter.bind(window, 'statechange', function(){
      set_locale_to(url('?locale'));
    });

    set_locale_to(localStorage.getItem("locale"));


    $('.switch-locale').on('click', 'a', function(e) {
      e.preventDefault();
      History.pushState(null, null, "?locale=" + $(this).data('locale'));
      localStorage.setItem("locale", $(this).data('locale'));
    });
  });
});

I'm open for other solutions if there are any.

Upvotes: 2

Related Questions