Pages

January 20, 2015

Component Directive Options over Multiple Attributes

Hi guys,

When building a directive component in AngularJS you'd probably ask yourself - how will I expose the component's API to the "outer world". Putting "events" and "data" aside for this one, I want to focus on the components behavior configuration.

I would like to share a direction which I tend to go with, and that's using a single "options" or "config" object which pretty much controls all the behavior (not the data, but rather what to do with it) aspects of component.

Let's take for example a component directive which display a chart, a bubble chart for instance. I would like to tell this component what are the colors palette it should use, where to put the legend, how to distribute the ticks on the axis etc.

Now, the naive way of approaching this is to set attributes for this directive and say "colors" attribute will hold the colors array. the "ticksinterval" will hold the ticks configuration and so forth. Before you know if, your component looks like a very very long line on the DOM, with numerous attributes each, BTW, creates it's own watcher and effects the overall performance greatly (if you bind it to the scope, which you probably do).

That should be enough of a reason to consolidate all these configurations into a single object, but there is a catch here -
When I do this I avoid registering any reference to executable code on the configuration object. The rule of thumb I follow is: "treat this configuration object as a JSON file that later can be loaded from a distant server", doesn't know the code, no callbacks, nothing.
So he question might rise - how will I execute API's over this component? I would like to select a single bubble in this chart, how do I do that?

So again, think of this "selectedBubble" as an attribute you would normally put on the directives  - something like "selectedIds" which receives an array of ID's and knows to track them down and mark them as selected on the chart.
That makes sense right? but wait - aren't we trying to avoid these multiple attributes? so instead, you've guessed it, put in on the configuration.
The component will know to read it from the configuration object and act upon it.

As with anything else, each "direction" or "rule" has it's exceptions and you should consider what suites the use-case best :)

Cheers

No comments: