jeudi 7 avril 2016

Using component lifecycle events in Ember

According to the latest Ember docs, using observers is discouraged in favor of overriding the component lifecycle hooks. What I'm not sure about is how to effectively use these hooks. The docs say that you can use didUpdateAttrs and didReceiveAttrs as replacements for observers.

So let's say that I have a component that charts out some data. The component looks something like:

{{my-chart data=data showLabels=showLabels otherProps=otherProps}}

When data is set, it needs to perform some analytics on the data, so this should only happen if data is truely new data. The showLabels attribute shows/hides labels in the chart and is toggled via something outside of my-chart.

I choose to use the didReceiveAttrs as it run on initial and subsequent renders, and coded it something like:

didReceiveAttrs() {
    let data = this.getAttr('data');
    this.performAnalytics(data);

    let showLabels = this.get('showLabels');
    this.updateHideLabels(showLabels);
}

The problem with this is that all the code within didReceiveAttrs is run every time any attribute is changed. So if the user repeatedly performs the action that causes showLabels to change, then performAnalytics is also called, which is bad since it causes the chart to refresh.

My specific question is, how do I use lifecycle events like didReceiveAttrs as an observer so that only the attribute that has changed has its code path executed?

I'll say that I tried storing off the attribute and comparing that to the incoming attribute, but I feel that's inefficient, especially in the case of data which is an array of complex objects.




Aucun commentaire:

Enregistrer un commentaire