我有以下模型:
var Car = Backbone.Model.extend({
url: "/save.php",
defaults: {
color: "red"
}
});
文档准备好后,我创建模型的一个新实例并保存它:
new volvo = new Car({color:"green"});
volvo.save();
然后在服务器中,我为新车分配一个 id 并将其返回给客户端(使用 PHP):
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
switch ($request_method) {
case 'post':
$data = json_decode(file_get_contents('php://input'));
$color = $data->{'color'};
$car = array('id'=>1, 'color'=>$color);
echo json_encode($car); //I use this to send the response to the client
//but I am not sure if this is the right way
break;
case 'put':
//code to handle this case
break;
}
问题是,当我想更新汽车模型沃尔沃的新实例时,主干假定沃尔沃始终是新模型,因此发出 POST 请求,但我希望它更新现有模型沃尔沃,例如这个:
new volvo = new Car({color:"green"});
volvo.save();
console.log( volvo.attributes ); //in here an id appears
console.log( volvo.get('id') ); //this returns 'undefined'
volvo.save({color:"red"}); //this saves in the database a new model, not desired
关于为什么会这样的任何想法?
谢谢