How to Share Model Data Among Unrelated Resources/Routes?


#1

What is the best way to share model data among resources/routes that don’t share a parent resource/route?

Details:

I have 2 top level resources whose model hooks retrieve almost the same data via Ajax. So their model hook code looks almost the same as well, i.e. not DRY. The difference is what they each do with that data. The goal is to keep their urls top level routes, like this:

example.com/#/resource1/...
example.com/#/resource2/...

not nested like this:

example.com/#/resource0/resource1/...
example.com/#/resource0/resource2/...

Question: How can I keep resource1 and resource2 ​top level resources/routes (not nest them within a common resource), but also not duplicate model hook code for each resource?


#2

You could:

  • use a mixin, service, or a model object that encapsulates all the common logic between the routes and then all you have to do is include, inject, or instantiate the mixin, service, or model.
  • nest them under a common route that has no path (I’ve not seen other people talk about this too much but it’s worked for me so far)

#3

If the data’s related to the whole application, you could also fetch it in the application route, and resource1 and resource2 could access it via this.modelFor('application').

If it’s not, I would stick it in a service, and memoize the data the first time it’s requested. This is essentially what you do to share session data across your app.


#4

Thank you, @samselikoff ! (a little late, sorry)


#5

Thank you, @varblob! (a little late, sorry)