Los navegadores parecen estar admitiendo cada vez más elementos personalizados, lo cual resulta muy útil para integrar JavaScript en programas Elm.
Veamos un ejemplo mínimo de cómo usar elementos personalizados para la localización e internacionalización.
Supongamos que queremos localizar fechas, pero esta funcionalidad aún no está disponible en los paquetes principales de Elm. Quizás quieran escribir una función que localice las fechas:
//
// localizeDate('sr-RS', 12, 5) === "петак, 1. јун 2012."
// localizeDate('en-GB', 12, 5) === "Friday, 1 June 2012"
// localizeDate('en-US', 12, 5) === "Friday, June 1, 2012"
//
function localizeDate(lang, year, month)
{
const dateTimeFormat = new Intl.DateTimeFormat(lang, {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
return dateTimeFormat.format(new Date(year, month));
}
Pero, ¿cómo usamos eso en Elm? Los navegadores más recientes permiten crear nuevos tipos de nodos DOM como este:
//
// <intl-date lang="sr-RS" year="2012" month="5">
// <intl-date lang="en-GB" year="2012" month="5">
// <intl-date lang="en-US" year="2012" month="5">
//
customElements.define('intl-date',
class extends HTMLElement {
// things required by Custom Elements
constructor() { super(); }
connectedCallback() { this.setTextContent(); }
attributeChangedCallback() { this.setTextContent(); }
static get observedAttributes() { return ['lang','year','month']; }
// Our function to set the textContent based on attributes.
setTextContent()
{
const lang = this.getAttribute('lang');
const year = this.getAttribute('year');
const month = this.getAttribute('month');
this.textContent = localizeDate(lang, year, month);
}
}
);
Las partes más importantes aquí son attributeChangedCallback y observedAttributes. Necesitas una lógica similar para detectar los cambios en los atributos que te interesan.
Cárgala antes de inicializar tu código Elm y podrás escribir código como este:
import Html exposing (Html, node)
import Html.Attributes (attribute)
viewDate : String -> Int -> Int -> Html msg
viewDate lang year month =
node "intl-date"
[ attribute "lang" lang
, attribute "year" (String.fromInt year)
, attribute "month" (String.fromInt month)
]
[]
Ahora puedes llamar a viewDate cuando necesites acceder a ese tipo de información localizada en tu vista.