Reputation: 100210
One thing I don't understand about Backbone is how it knows which objects in the database to sync with. I am using MongoDB on the backend - how do I tell Backbone to generate MongoDB style ObjectIDs to store in the DB (perhaps Backbone just gets the IDs from Mongo - but if not how do I guarantee this Backbone generated IDs are unique in comparison to the MongoDB generate ObjectIDs?) The main problem I am having is that no Backbone.Model id is appended to the end of the root url I define in my Model upon a PUT or DELETE call.
here is my model:
var team = document.getElementsByName('team');
console.log(team);
var Player = Backbone.Model.extend({
defaults: {
ID: "",
team: team,
firstName: '',
lastName: '',
age: '',
phone: '',
email: ''
},
idAttribute: "ID",
urlRoot: 'http://localhost:3000/api/players'
});
var PlayerCollection = Backbone.Collection.extend({
model: Player
});
here is the view:
var addPlayerView = Backbone.View.extend({
tagName: "div",
id: 'addPlayerDiv',
events: {
'click #submitNewPlayer': 'onAddPlayer',
'click #cancelNewPlayer': 'cancelAddPlayer'
},
initialize: function () {
},
render: function () {
var playerTemplate = document.getElementById('add-player-template').innerHTML;
this.$el.html(_.template(playerTemplate)());
return this;
},
onAddPlayer: function (event) {
event.preventDefault();
var data = form2js('add-player-template-form','.',true);
this.model.set({id:data.age,age:data.age,phone:data.phone,email:data.email});
this.model.save();
$(this.el).removeData();
this.unbind();
this.remove();
window.mainManageRosterView.render();
}
});
and here is where I initialize a new view with a new model instance:
<script>
function addNewPlayer(event) {
event.preventDefault();
var player = new Player({}); //perhaps this is incorrect, the id is null/undefined after all
var newPlayerView = new addPlayerView({el: $("#addPlayerDiv"), model: player});
var rendered = newPlayerView.render();
$(rendered.el).appendTo(this.$el).hide().fadeIn().slideDown();
};
</script>
Surely I am doing something wrong. The model is definitely not undefined in the view, but it has no ID. How do I give my Backbone model an ID? Perhaps Backbone only gives the model an id after it is saved?
To reiterate, the main problem I am having is that Backbone is not automatically appending an ID to the end of the root URL that I defined above in the model:
PUT /api/players/ 404 319ms - 475b
but it should look like this:
PUT /api/players/[mongoDB ObjectID here] 200 319ms - 475b
so basically, the ID is missing, and I don't know why. Furthermore, why the hell is Backbone doing a PUT? Shouldn't it being a POST if it's the first time it's saving this model?
Upvotes: 0
Views: 451
Reputation: 181
Is it possible, that the ID
is not defined, because you just define the id
?
You are using this.model.set({id:data.age, ...
(lowercase) to define your identifier.
But defined idAttribute: "ID",
(uppercase) as ID Attribute.
Upvotes: 1