Last active
January 28, 2023 01:25
-
-
Save runspired/f5eae52862388554495f82195f15471f to your computer and use it in GitHub Desktop.
Module Scope Reactive Strings Example
This file contains 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
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; | |
} | |
} |
This file contains 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
{ | |
"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