我有以下模型:
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
关于为什么会这样的任何想法?
谢谢
检查这个例子:
var volvo = new Car({color:"green"});
// Create a new car model.
console.log(volvo.isNew()); // Output: true
volvo.save();
console.log(volvo.isNew()); // Output: false
console.log(volvo.id); // Output: 1
// Update the color of the already created model to red.
volvo.save({color:"red"});
现在,如果你想在代码的另一部分获取已经创建的模型,你必须知道id。
var volvo = new Car({id: 1});
// Update the model.
console.log(volvo.isNew()); // Output: false
volvo.save({color: "blue"});
Remarque:服务器应返回使用 id 创建的模型的 JSON。
希望这对:)有帮助
检查你是否真的在帖子响应中发送了 id 属性。没有 id 的模型被视为新模型,因此在保存时会创建而不是更新。