can-connect/constructor/constructor
Adds the ability to operate on special types instead of plain JavaScript Objects and Arrays.
constructor( baseConnection )
Adds methods that allow the connection to operate on special types.
Parameters
- baseConnection
{connection}:A connection with most of the DataInterface implemented.
Returns
{connection}:
A new connection with the additional methods.
Use
The can-connect/constructor/constructor behavior allows you to hydrate the raw, serialized representation of
your application's data into a typed representation with additional methods and behaviors.
For example, you might want to be able to load data as a particular JavaScript Constructor function that has a helper methods that act upon the serialized data.
An example might be loading data from a "/todos" service and being able to call .timeLeft()
on the todos that you get back like:
todoConnection.get({id: 6}).then(function(todo){
todo.timeLeft() //-> 60000
})
The following creates a todoConnection that does exactly that:
var Todo = function(data){
for(var prop in data) {
this[prop] = data;
}
};
Todo.prototype.timeLeft = function(){
return new Date() - this.dueDate
};
var todoConnection = connect([
require("can-connect/constructor/constructor"),
require("can-connect/data/url/url")
],{
url: "/todos"
instance: function(data){
return new Todo(data);
}
});
The constructor extension is still useful even if you want to keep your data as plain
JavaScript objects (which its default behavior). The constructor extension describes
the in-memory representation of your data on the client. Other extensions need to know this
representation for advanced behavior like can-connect/real-time/real-time or can-connect/fall-through-cache/fall-through-cache.
CRUD Methods
The constructor extension supplies methods that create, read, update and
delete (CRUD) typed representations of raw connection data.
CRUD Callbacks
The constructor function "CRUD Methods" call "CRUD Callbacks" with the
the "data interface" response data. These callbacks update the state of
the typed representation.
Instantaitors
These methods are used to create a typed instance or typed list given raw "data interface" objects.
Serializers
These methods convert the typed instance or typed list into a representation for the "data interface".