4 ms·
A lens is an object that has both read and write access to a property of an object (or to a path into a tree of nested objects). Rather than passing parts of t
by pygy_ 9y ago
A lens is an object that has both read and write access to a property of an object (or to a path into a tree of nested objects).
Rather than passing parts of the model to the children (as you'd do with React props), you pass lenses into said parts.
It enables child components to read/write to the global store without knowing its structure. As long as it receives an appropriate (set of) lens(es) it is happy.
So, for example, if you have a list of strings, rather than passing the nth string to the nth component, you'd pass a lens to the nth string. The component can then not only read but also write to its slot.
Lenses can also be composed, so you can create them on the go as you'd pass sub-props to grand-children.
https://github.com/calmm-js/partial.lenses https://github.com/calmm-js/partial.lenses <= a comprehensive lens library
http://ramdajs.com/ http://ramdajs.com/ also has lenses.
These libs are strongly influenced by the FP world. The underlying data structures are immutable, writing to a lens creates a new version of the store (as efficiently as possible, by recycling intact objects).
- colordrops 9y agoThank you.
- charlieflowers 9y agoSo basically, it's like using dependency injection, and what you're injecting are higher order functions for the getters and setters for whatever properties you need. Is that right?
- harperlee 9y agoDo they need to be functions? Because this seems a lot like handling [:a :keyword :vector :for :navigating :trees] in Clojure and passing it to either update-in or get-in functions, which is a pattern ubiquitous in re-frame, but not sure is can be called a lens).
- charlieflowers 9y agoWhat you're saying sounds similar. But my question and your post are both missing the "composition" aspect. Somehow lenses are composable, and I guess to grok that we'd need to look deeper.
- pygy_ 9y agoSounds about right.
- KirinDave 9y agoPureScript's thermite is what I had in mind, but yeah this is good.