DEV Community


Define your Custom Elements functionally

Tal Weinfeld
・1 min read

I've been using custom elements a lot lately, they're great fun!

The only thing that bothers me, as a "functional-style" developer, is the class-based definition interface: It feels a bit awkward to parcel my code according to it instead of my actual concerns. So I keep finding myself write the same boilerplate code which relays lifecycle events to the constructor, where I can handle them all in a tidier fashion (using RxJS or Kefir).

That's why I've created Element-F. A functional-style wrapper for defining custom elements, in which a definition looks like this:

window.customElements.define('my-world', ElementF(function(life){

  const WORLD_DICT = {
    "spanish": "mundo",
    "french": "monde",
    "german": "welt",
    "russian": "mir",
    "chinese": "δΈ–η•Œ"

  const spanEl = document.createElement('span');  
  life.once('connect', ()=> this.appendChild(spanEl));
  life.on('attribute:lang', ({ newValue })=> spanEl.textContent = WORLD_DICT[newValue] ?? "world");

}, ["lang"]));
Enter fullscreen mode Exit fullscreen mode

Live demo

Feel free to share your impressions πŸ™‚

Discussion (0)