-
-
Save EnTeQuAk/9327ffaa730abfb163bf45655f167e0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// i18n data that get's passed to jed | |
let DEFAULT_I18N_DATA = { | |
messages: { | |
en: { | |
'This is a test': 'This is a test', | |
}, | |
fr: { | |
'This is a test': 'C\'est un test', | |
}, | |
ja: { | |
'This is a test': 'これはテストです', | |
} | |
} | |
} | |
// Our dummy Jed object, initialize this for real with `var jed = Jed()` | |
class Jed { | |
constructor(i18ndata, locale) { | |
this.options = { | |
locale_data: i18ndata, | |
} | |
// For our dummy only... | |
this.locale = locale; | |
} | |
// This is the main function that get's always called by Jed it seems, see | |
// https://github.com/messageformat/Jed/blob/master/jed.js#L171-L225 | |
// for a few more details. | |
// So let's use this for our proxy magic :) | |
dcnpgettext(domain, context, singular_key, plural_key, val) { | |
// *VERY* simplified what happens inside Jed, obviously the real | |
// implementation is much more complex. for presentation only :D | |
return this.options.locale_data.messages[this.locale][singular_key]; | |
} | |
// Actually copied from Jed | |
gettext(key) { | |
let handler = { | |
get(target, prop, receiver) { | |
if (typeof prop === 'symbol') { | |
return function (value) { | |
return this.dcnpgettext.call(this, undefined, undefined, key); | |
}; | |
} else { | |
return Reflect.get(target, prop); | |
} | |
} | |
}; | |
return new Proxy(this, handler); | |
} | |
// Needs to be set on `Jed` -> `Jed.setLocale = function() {...}` | |
setLocale(newLocale) { | |
// this.options.locale_data = require('messages/${locale}/messages.js'); | |
this.locale = newLocale; | |
} | |
} | |
let i18n = new Jed(DEFAULT_I18N_DATA, 'en'); | |
i18n.setLocale('en'); | |
const myMessage = i18n.gettext('This is a test'); | |
console.log('TRANSLATING STARTS HERE'); | |
console.log('Translated:', myMessage); | |
i18n.setLocale('fr'); | |
console.log('Translated:', myMessage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment