Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing data between ViewModels in knockout.js

I have an array of items populated by an AJAX call in a knockout ViewModel, which displays a few fields of data for each item on a web page.

Now I need to enable the user to click on one item populating a side bar with data which was received from the previous AJAX request (a few fields plus a lot more).

I suppose typically one would take an id and do an item specific AJAX request, routing it through Sammy.js, but we don't need to.

I'm new to knockout; best policy I imagine is to have a ViewModel for the various divs to display the data, but how to get the ViewModels to pass data between themselves? Is this taboo?

  • Making reference to the other window via the window object?
  • Using the with: keyword? It keeps cropping up, but I can't see how to apply that in this context.
  • Perhaps going via Sammy.js, and caching the data in Amplify?

This is an example of drill-down functionality, and I've read a number of StackOverflow Q&A about this but couldn't find up something I can use. I've got up to this stage by following John Papa's PluralSight tutorial.

like image 687
zeristor Avatar asked Feb 18 '23 10:02

zeristor


2 Answers

You may want to go with a pub/sub model either with Amplify's messaging or the library the @RPNiemeyer mentions above. Both are excellent.

However it sounds like you just want to grab the data from the server, then use that data in multiple view models. Perhaps even sharing some of that data in multiple view models. The datacontext concept in my SPA tutorial allows you to host data in the datacontext and reference it from other view models.

You could also use a library like Breeze to help do this (Breeze would replace the datacontext in my SPA ... and be better at it as I will show in an upcoming course).

These are just a few options

like image 180
John Papa Avatar answered Feb 21 '23 01:02

John Papa


You may also want to checkout the "Share an EntityManager" post under "Cool Breezes" in the breeze documentation.

The sharing a single EntityManager is probably all you need. But if you think you need more than one, read "Multiple managers".

like image 36
Ward Avatar answered Feb 21 '23 02:02

Ward