E
E
Eugene2012-05-30 18:12:37
JavaScript
Eugene, 2012-05-30 18:12:37

How to organize the localization of a Backbone.js application?

In this case, localization and internationalization can be considered synonymous

. So far, I decided for myself to store the locale settings in a separate Backbone model and pass it to each view.
Maybe you can suggest a more interesting and elegant solution.

// набор параметров локали/интернационализации
var i18n = {
    en : {
        language : 'English',
        greeting : 'Hello'
    },
    ru : {
        language : 'Русский',
        greeting : 'Привет'
    }
};

// В самой модели локали ничего особенного
var LocaleModel = Backbone.Model.extend();

// Некая модель (для примера не имеет значения)
var MyAppModel = Backbone.Model.extend();

// Вьюха приложения, использующая данные локали
var MyAppView = Backbone.View.extend({

    initialize: function(options)
    {
        this.i18n = options.i18n;
        this.i18n.bind('change', this.onLocaleChange, this);
    },

    setLocale: function(locale)
    {
        this.i18n.set(i18n[locale]);
    },

    onLocaleChange: function()
    {
        console.log('locale has been changed to: ' + language);
    }
});

var locale = new LocaleModel(i18n.en);
var app = new MyAppView ({
    model : new MyAppModel({username:'John Doe'}),
    i18n  : locale 
});


// Совсем другая вьюха, но она так же использует текущую локаль
// Смена локали в любом месте затрагивает все подвязанные представления
var OtherAppView = Backbone.View.extend({
    ...
});

var otherApp = new OtherAppView({
    model : new OtherModel(),
    i18n  : locale 
});

locale change example
app.setLocale('ru');

in the context of MyAppView, you can access the locale settings in this way
this.i18n.get('language');


View a simple usage example

UPD:
The locale is a global object and is passed to different views.
// Мы можем сменить локаль и на это событие отреагируют все подписанные представления.
locale.set(i18n.ru);

Answer the question

In order to leave comments, you need to log in

6 answer(s)
K
Konstantin Kitmanov, 2012-05-30
@k12th

It seems to me that locale is purely about presentation. Accordingly, its place in the templates.
It is better not to use models for this at all, because Backbone.Events can be "stuffed" into any .

K
kuzemchik, 2012-05-30
@kuzemchik

I structure the application using require.js, there is a module with examples for it requirejs.org/docs/api.html#i18n
Changing the locale is a global event (unless you have a dictionary interface or something where there are several parts on different languages). I would leave it global instead of dragging the model around with me. In addition, pulling all locales at the same time is a lot.

S
Shedal, 2012-05-30
@Shedal

And I think you did pretty well. The only thing I would do is put the LocaleModel object inside the MyAppView. So somehow it turns out more structured.
Why don't you like this decision?
PS bind() and unbind() are deprecated underscore functions. Starting with some version there, you need to use on () and off ().

A
Alexey Prokhorov, 2012-05-30
@megahertz

Usually I take out localization separately, I implemented it as in Yii, including with support for declension of numerals. I haven’t published the code anywhere yet, my hands don’t reach to decorate it beautifully, but if anyone likes it, I can share it:
App.messages.ru = {
    main: {
        'Hello {subject}': 'Привет'
    }
};
...
var text = App.t('main', 'Hello {subject}', {'{subject}': 'Мир'});

S
Sergey, 2012-05-30
Protko @Fesor

Why store the locale in the model?

P
personaljs, 2014-01-02
@personaljs

requirejs.org/docs/api.html#i18n

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question