When Components Aren't Enough

Ilya

2024-03-10T18:45:08.715Z
https://ilyaradchenko.com/notes/cltlv6sq2000vn3bbdhe2ygms

By Ilya on 3/10/2024, Seedling - EmberJS

Sometimes components are too high-level, and you need to get at a specific DOM element, either for scrollTo or focus, in these situations Ember provides a lower-level primitive called an element-modifier. To get started with element modifiers you can check out existing modifiers at EmberObserver or create your own using the ember-modifier library.

Some Examples

Which will focus the first non-disabled input that it finds (from ember-autofocus-modifier).

Which will scroll to the element once it's in the DOM, and is super easy to implement:

There is also the ref modifier from ember-ref-modifier which gives you access to the element:

Along with {{on-click-outside}} from ember-click-outside.

Why Are Element Modifiers Useful?

Mainly because you can do things like:

Which handles the setup and teardown of the element, so if isEditorVisible turns false the editor initialized on our element will be properly cleaned up. This is important because the new Glimmer Components allow multiple top-level elements without any kind of fragment syntax.

Note: I'm using ember-render-modifiers in the above example. But you could create a modifier to encapsulate both the setup and teardown so reusability is easier.

brush and pen
Home