save
Create or update an instance on the connection data source
connection.save( instance )
First checks if the instance has an id or not. If it has an id, the instance will be updated; otherwise, it will be created.
When creating an instance, the instance is added to the cidStore, and its
serialized data is passed to
createData. If createData
's promise resolves to anything other than undefined
,
createdInstance is called with that data.
When updating an instance, its serialized data is
passed to updateData. If updateData
's promise resolves to anything other than
undefined
, updatedInstance is called with that data.
Parameters
- instance
{Instance}
:the instance to create or save
Use
To use save
to create an instance, create a connection, then an instance, and call .save()
on it:
// Create a connection
var constructor = require('can-connect/constructor/');
var dataUrl = require('can-connect/data/url/');
var todoConnection = connect([dataUrl, constructor], {
url: "/todos"
});
// Create an instance
var todo = {name: "do dishes"};
// Call .save()
todoConnection.save(todo)
.save(todo)
above will call createData
on the data/url
behavior, which will make an HTTP POST request to /todos
with the serialized todo
data. The server response
data may look something like:
{
id: 5,
ownerId: 9
}
That data will be passed to createdInstance which by default
adds those properties to todo
, resulting in todo
looking like:
{
name: "do dishes",
id: 5,
ownerId: 9
}
As an example of updating an instance, change a property on todo
and call .save()
again:
// Change a property
todo.name = "Do dishes now!!";
// Call .save()
todoConnection.save(todo)
The .save(todo)
above will call updateData
on the
data/url behavior, which will make an HTTP PUT request to /todos
with the serialized todo
data.
A successful server response body should look something like:
{
name: "Do dishes now!!",
id: 5,
ownerId: 9
}
This data will be passed to updatedInstance which by default sets
all of todo
's properties to look like the response data, even removing properties that are missing from the
response data.