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

Re : Is this a safe strategy for translating can.Map/can.Model attribute names prior to init()?

$
0
0
I wouldn't instantiate directly (my tests case was simply to show why parseModel didn't work). 

I would likely be instantiating via can.List.Map or can.Map.prototype.define instead.

Let me paint a picture of the backend API we're dealing with:

We have an endpoint that returns "products", for which we have defined a model that implements findOne and findAll. No problem there.

Example response:

  1. [
  2.       { 
  3.             legacyItemNo: 123, 
  4.             displayName: 'Some Product', 
  5.             enteredQuantity: 0
  6.       },
  7.       { 
  8.             legacyItemNo: 456, 
  9.             displayName: 'Some Other Product', 
  10.             enteredQuantity: 0
  11.       },
  12.       {...},
  13.       {...}

We have another endpoint that returns an "order review", and in this response, one of the properties is an array that closely resembles what we get back from the "products" endpoint. We have also defined a model for this, which implements a findOne method.

Example response:

  1. {
  2.       totalPrice: 123.00,
  3.       itemCount: 4,
  4.       deliveryInfo: { ... },
  5.       products: [
  6.             { 
  7.                   legacyItemNo: 456, 
  8.                   displayName: 'Some Other Product', 
  9.                   enteredQuantity: 0
  10.             },
  11.             { 
  12.                   legacyItemNo: 456, 
  13.                   displayName: 'Some Other Product', 
  14.                   enteredQuantity: 0
  15.             },
  16.             {...},
  17.             {...},
  18.             {...}
  19.       ]
  20. }
For both of these responses, we need to convert the attribute names for the products themselves (as well as provide other computed methods). So in a nutshell, we need to sometimes treat sub properties of one model as if they are instances of another model. The current solution for doing this is to use can.Map.prototype.define to cast the "products" attribute as an instance of a "product list".


  1. var OrderModel = can.Model.extend({
  2.   findOne: function () {...}
  3. }, {
  4.   define: {
  5.     products: {
  6.       Type: Product.List
  7.     }
  8.   }
  9. });




Viewing all articles
Browse latest Browse all 3491

Trending Articles