models

  • function
can.Model.models  

Convert raw data into can.Model instances.

can.Model.models(data[, oldList])

Parameters

  1. data {Array<Object>}

    The raw data from a findAll() request.

  2. oldList {can.Model.List}Optional

    If supplied, this List will be updated with the data from data.

Returns

{can.Model.List}

A List of Models made from the raw data.

models: "PROPERTY"

Creates a models function that looks for the array of instance data in the PROPERTY property of the raw response data of findAll.

can.Model.models(data, xhr) is used to convert the raw response of a findAll request into a can.Model.List of model instances.

This method is rarely called directly. Instead the deferred returned by findAll is piped into models. This creates a new deferred that resolves to a can.Model.List of instances instead of an array of simple JS objects.

If your server is returning data in non-standard way, overwriting can.Model.models is the best way to normalize it.

Quick Example

The following uses models to convert to a can.Model.List of model instances.

Task = can.Model.extend()
var tasks = Task.models([
  {id: 1, name : "dishes", complete : false},
  {id: 2, name: "laundry", compelte: true}
])

tasks.attr("0.complete", true)

Non-standard Services

can.Model.models expects data to be an array of name-value pair objects like:

[{id: 1, name : "dishes"},{id:2, name: "laundry"}, ...]

It can also take an object with additional data about the array like:

{
  count: 15000 //how many total items there might be
  data: [{id: 1, name : "justin"},{id:2, name: "brian"}, ...]
}

In this case, models will return a can.Model.List of instances found in data, but with additional properties as expandos on the list:

var tasks = Task.models({
  count : 1500,
  data : [{id: 1, name: 'dishes'}, ...]
})
tasks.attr("name") // -> 'dishes'
tasks.count // -> 1500

Overwriting Models

If your service returns data like:

{thingsToDo: [{name: "dishes", id: 5}]}

You will want to overwrite models to pass the base models what it expects like:

Task = can.Model.extend({
  models : function(data){
    return can.Model.models.call(this,data.thingsToDo);
  }
},{})

can.Model.models passes each instance's data to can.Model.model to create the individual instances.