Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Re : Proper way to handle nested data with can.Model

$
0
0
You can use the can.observe.attributes plugin for this: when an instance for your 'outer' model is created, it can auto-convert the arrays of data into Lists of Sales and CustomerPricing instances.

(Note that you always need a unique id for each model instance: you can get some weird results if multiple instances in a list have the same id. If you ever find that your list contains 2 or more references to the same model instance, that's a non-unique id issue.)


Updating the nested list is a little trickier, since retrieving a list will always create a new list instance -- unlike models, where retrieving an already-loaded model will update your existing model instance. (So, the lists of Sales and CustomerPricing instances which the attributes plugin auto-creates for you won't be updated when you retrieve a new Sales or CustomerPricing list.)

We handled this by creating our own persistent list, and updating it whenever a new list comes in. It looked something like:
  1. var salesYearList = new SalesYearModel.List();
  2. // Whenever we load a product view, we update our list from it:
  3. ProductViewModel.findOne( ..., function(product) {
  4.       salesYearList.replace(product.attr("Sales"));
  5. });
  6. // And, whenever we load a new list of sales years, we update our list from that
  7. SalesYearModel.findAll( ..., function(yearList) {
  8.       salesYearList.replace(yearList);
  9. });
  10. // And then we only use our salesYearList in our ejs templates; we *don't* use or bind to product.attr("Sales") or the yearList


Edit: It looks like the List.replace() function accepts a Deferred as well, so salesYearList.replace( SalesYearModel.findAll( ...) ) should work as well.

Viewing all articles
Browse latest Browse all 3491

Trending Articles