Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  44] [ 7]  / answers: 1 / hits: 41302  / 12 Years ago, wed, july 11, 2012, 12:00:00

I have some code where I want a NoteCollectionView to add a new Note to the NoteCollection. This is triggered by a function newNote in the NoteCollectionView:



newNote: function(data) {
var note = new Note(data);
this.collection.add(note);
},


I'm still very new to backbone, and I want to make sure this syncs with the server. The concerns I have are:



1) Will simply adding this note to the collection trigger a save() from the server, and update the model with the ID that the server gives it? Or,



2) If the server does not update my model and give me an actual ID, how do I save the model with note.save() and get back an ID from the server?


More From » backbone.js

 Answers
83

To address your first question, no, .add will not trigger any kind of call to the server; it will only add a model to a collection.



However, you do have a couple options. One would be to create the new note model, save it to the database, and then add it to the collection:



newNote: function(data) {
var note = new Note(data);
note.save();
this.collection.add(note);
}


The second option is to simply use Backbone's collection.create method. Give it a hash of attributes and it will




  1. Create the model

  2. Save it to the database

  3. Add it to the collection



All in one fell swoop, like so:



newNote: function(data) {
return this.collection.create(data);
}


collection.create also returns the newly created model, illustrated by my return statement above.


[#84327] Tuesday, July 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;