save

  • function
can.Model.prototype.save  

Save a model back to the server.

model.save([success[, error]])

Parameters

  1. success {function()}Optional

    A callback to call on successful save. The callback recieves the can.Model after saving.

  2. error {function()}Optional

    A callback to call when an error occurs. The callback receives the XmlHttpRequest object.

Returns

{can.Deferred}

A Deferred that resolves to the Model after it has been saved.

model.save([success(model)],[error(xhr)]) creates or updates the model instance using create or update depending if the instance has an id or not.

Using save to create an instance.

If save is called on an instance that does not have an id property, it calls create with the instance's properties. It also triggers a "created" event on the instance and the model.

// create a model instance
var todo = new Todo({name: "dishes"})

// listen when the instance is created
todo.bind("created", function(ev){
     this //-> todo
})

// save it on the server
todo.save(function(todo){
     console.log("todo", todo, "created")
});

Using save to update an instance.

If save is called on an instance that has an id property, it calls create with the instance's properties. When the save is complete, it triggers an "updated" event on the instance and the instance's model.

Instances with an id are typically retrieved with findAll or findOne.

// get a created model instance
Todo.findOne({id: 5},function(todo){
         
  // listen when the instance is updated
  todo.bind("updated", function(ev){
       this //-> todo
  })

  // update the instance's property
  todo.attr("complete", true)
  
  // save it on the server
  todo.save(function(todo){
       console.log("todo", todo, "updated")
  });

});