Skip to content

Instantly share code, notes, and snippets.

@runspired
Last active January 28, 2023 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runspired/f5eae52862388554495f82195f15471f to your computer and use it in GitHub Desktop.
Save runspired/f5eae52862388554495f82195f15471f to your computer and use it in GitHub Desktop.
Module Scope Reactive Strings Example
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
const translations = {
'en': {
greeting: 'Welcome Ember friends!'
},
'es': {
greeting: 'Hola Embereños!'
}
}
// close over intl in module scope from wherever it is instantiated
let intl;
class Intl {
constructor() {
intl = this;
}
@tracked locale = 'en';
t(key) {
return translations[this.locale][key];
}
}
// T here wraps a translation so that
// the value can be passed around but it can
// still react to changes to intl.locale
class T {
get value() {
return intl.t(this.key);
}
constructor(key) {
this.key = key;
}
toHTML() {
// should we need to do a safe-string
// we'd implement this
return intl.t(this.key);
}
toString() {
return intl.t(this.key);
}
}
// just pretending we are using a service here
function service() {
intl = new Intl();
return intl;
}
// a user would import this and could even use it
// in module scope
function formatMessage(key) {
return new T(key);
}
// example module scope value
const AppGreeting = formatMessage('greeting');
export default class ApplicationController extends Controller {
intl = service();
greeting = AppGreeting;
@action
setLocale(str) {
// this doesn't update the template
// because glimmer doesn't call toString/toHTML within
// the tracking context.
this.intl.locale = str;
}
}
<h1>{{this.greeting}}</h1>
<br>
<button {{on "click" (fn this.setLocale "es")}}>Use Spanish</button>
<button {{on "click" (fn this.setLocale "en")}}>Use English</button>
<br>
{{outlet}}
<br>
<br>
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"@glimmer/component": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment