私は次のモデルを持っています:
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;
}
問題は、車のモデル volvo の新しいインスタンスを更新したい場合、backbone は volvo が常に新しいモデルであると想定しているため、POST で要求が行われますが、既存のモデル volvo を更新したいということです。これ:
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
これはなぜですか?
ありがとう