How to create *static* property in can.Model

113 Views Asked by At

I need somehow to store metadata in the can.Model I use findAll method and receive such JSON:

{
    "metadata": {
        "color": "red"
    },
    "data": [
        { "id": 1, "description": "Do the dishes." },
        { "id": 2, "description": "Mow the lawn." },
        { "id": 3, "description": "Finish the laundry." }
    ]
}

I can work with data like can.Model.List, but I need metadata like a static property or something.

1

There are 1 best solutions below

0
On

You can use can.Model.parseModels to adjust your response JSON before it's turned into a can.Model.List.

parseModels: function(response, xhr) {
  var data = response.data;
  var metadata = response.metadata;
  var properties;

  if(data && data.length && metadata) {
    properties = Object.getOwnPropertyNames(metadata);

    can.each(data, function(datum) {
      can.each(properties, function(property) {
        datum[property] = metadata[property];
      });
    });
  }

  return response;
}

Here's a functional example in JS Bin: http://jsbin.com/qoxuju/1/edit?js,console