4 ms·
I'm curious what happens when you want to share models across components. In angular.js you would use services to do this, but what's the analog in React?
by marknutter 13y ago
I'm curious what happens when you want to share models across components. In angular.js you would use services to do this, but what's the analog in React?
- Touche 13y agoIf you're passing it to child components you pass it through attributes. If you're passing up to parents, however, you have to create a function on the parent that will get called to accept the child's new data. This can get really messy if you have deeply nested components and need to get data from one branch to another branch.
- rok3 13y agoReact encourages you to use a parent component that controls the state and passes it down to it's children via props. Passing data to separate components without a shared parent is outside of what React is trying to accomplish but I've handled it before by passing a Backbone model to the separate components as props.
- fiatjaf 13y agoI have been successful by instantiating separate services to perform REST operations and a global event emitter to establish communication between all the services and all the components that relate to these services in any way.
- marknutter 13y agoI cringe when I hear the words "global" and "event" together in the same sentence. Projects I've worked on in the past that relied heavily on global events often became a maintainability nightmare.
- fiatjaf 13y agoWhy? Please share your experiences. I don't understand what's the utility of event emitters if not for serving as glue to all the separate components of an app. Am I wrong?
- marknutter 13y agoYou're not wrong. It's definitely one way to solve it. I just find it harder to jump into a project with heavy reliance on global events and be able to quickly understand what's going on. It gets even harder if you have events firing other events.
- ninkendo 13y ago> I just find it harder to jump into a project with heavy reliance on global events Harder than what?
- marknutter 13y agoHarder than the way that it is done in Angular, via services.