Hacker News new | past | comments | ask | show | jobs | submit login

It’s also good for data formatting. You don’t want to see 22.2222222C for 72F. Ideally when you adjust one, the values are internally consistent.



Good point. This in turn shows the risk of endless event propagation loops: So you decide to solve the formatting problem by using floor() and only showing the integer parts.

So now when the user enters 72°F, it shows 22°C. However, in a naive implementation, updating the celsius field would trigger a change in the other direction as 22°C converted back would round to 71°F. But 71°F rounds to 21°C, triggering another change, etc etc.


Vuejs has a interesting and great way to avoid such feedback loops even in the presence of 2-way data binding. Most importantly you wouldn't use any watchers/effects to trigger logic on property-updates, but rather you use what they call computed property, which can do conversion on the fly, in both directions, giving different behavior on read and write.

    celcius: {
        get() { return this._inputCelcius || ctof(this._inputFahrenheit) }
        set(newVal) {
            this._inputCelcius = newVal
            this._inputFahrenheit = null
        }
    }
Repeat for fahrenheit. Now i've seen shorter examples but most of them are very coupled to the UI, with each event on textbox writing directly to the other textbox attributes, this property can be bound to any number of textboxes and sliders without any additional code to keep them in sync. Similar techniques can be used for more complex synchronizations with conversions, like a date picker that allows both text-input and clicking a calendar.


An interesting solution would account for the precision of the user input when formatting other fields, with different results for 72 and 72.000





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: