After our last refactoring, the ember-cli-autocomplete component no longer
uses observers. However, the list of parameters the outermost, container
component, auto-complete returns is now unwieldily long:

Not only does that look clumsy, it also makes refactoring more difficult and one
always constantly have to flip between the component’s template (where params
are yielded from) and the template where the component is used to see if the
position of values match. So how can improve this?

Components as functions

To understand several concepts about components, consider them functions.
Putting aside the fact that they can also emit DOM elements, you call them with
a list of arguments, usually, though not exclusively, a collection of key-value
pairs. The component then does some internal stuff and returns a value from its
template via the yield keyword.

Our current case is another instance when treating them as functions can help us
find the solution. Ask yourself: what would you do if the return value of a
function you wrote grew to a long list of arguments? You would convert the
return value to a key-value collection, such as a hash, wouldn’t you?

Well, in Ember’s component land, we can do this by using the hash helper,
introduced in Ember 2.3. It takes a list of key-value pairs at invocation
time and outputs an object (a hash) with them:

1
2
3

{{#with(hashfirstName='Mike'lastName='McCready'instrument='guitar')as|musician|}}
Hello, I'm {{musician.firstName}}{{musician.lastName}} and I play the {{musician.instrument}}.
{{/with}}

We can use the hash helper to bring some sanity to the return value of auto-complete
parameters. It currently looks like this:

Instead of the long list of parameters, auto-complete now yields a single hash
parameter (called params above), whose keys are used in the child components
(params.isOpen, params.options, etc.)

Polyfill it

Since we want our component to be usable not only in Ember >=2.3 applications,
where the hash helper is built in, we should add the
ember-hash-helper-polyfill, which makes the hash helper available in earlier
Ember versions, as a dependency of the addon:

Wrapping up

That wraps up my Complex Component Design in Ember.js series. Our component
improved by each post and I think we now have a pretty flexible and thus
reusable component. The main purpose of the series, however, is education, so I
hope that I was able to transfer some of the knowledge I’ve acquired by building
components.

If you would like to read the whole series as a pdf, just give my your email
address below and I’m sending it to you.