Observing changes to interdependent properties

35 views
Skip to first unread message

Michael Giuffrida

unread,
Jul 2, 2015, 12:25:41 AM7/2/15
to polymer-dev
Hi,

I'm struggling with property observation in elements with properties that depend on each other. I keep running into infinite loops but I feel like this should be easy to fix.

Suppose I have a <color-picker> element with six properties: red, green, blue, hue, saturation, lightness. I'd like to be able to set any one of these properties, and have the other properties automatically update. For example, if I set one or more of the RGB properties, the equivalent HSL properties should update. And vice versa.

I have two observers:
* 'rgbChanged(red, green, blue)', which sets the HSL based on the new RGB
* 'hslChanged(hue, saturation, lightness)', which sets the RGB based on the new HSL

The problem is that changing one set of values will cause the other set of values to be changed, causing the other observer to also be called.

Best case scenario: wasteful calculation. if I set RGB, rgbChanged calculates HSL, then hslChanged calculates RGB. This is redundant; these RGB values should be the same as the RGB I set originally.

Worst case scenario: the two functions aren't perfectly symmetrical, due to rounding error. Now the observers will trigger each other until I reach the stack size limit.

In a non-Polymer world, I would probably handle this by adding a "isUpdating" flag, and clear the flag in a setTimeout after changing properties. Is there a Polymeric way of handling this?

Thanks.
Michael

Elliott Sprehn

unread,
Jul 3, 2015, 2:50:52 AM7/3/15
to Michael Giuffrida, polymer-dev
Fundamentally the issue you have here is that you have two competing sources of truth and because HSL and RGB cannot actually be converted back and forth without data loss they fight with each other forever. This would also cause an infinite loop in Angular and other frameworks. Having that isUpdating flag just hides the fact that the two sources are fighting and you're losing data when you fail to update because of the isUpdating flag being set which means instability in your data model.

The solution is to pick one source of truth and derive the other value only when needed. I'd suggest <color-picker> should have r/g/b attributes and toHSL()/setHSL() methods.

Follow Polymer on Google+: plus.google.com/107187849809354688692
---
You received this message because you are subscribed to the Google Groups "Polymer" group.
To unsubscribe from this group and stop receiving emails from it, send an email to polymer-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/polymer-dev/CACi5S_14nT2p2-%3D1Sq3vXTJHtVxbr86EsFHjTukBcbNG9R38Xg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages