Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: Adding a model to a collection from a collection view?

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?

like image 652
theeggman85 Avatar asked Jul 11 '12 17:07

theeggman85


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Which is considered the backbone of any HTML document?

js (aka Backbone) is designed to add structure to client-side applications, to avoid a spaghetti-code mess.

What is El property of backbone JS view?

It defines which element to be used as the view reference. The this. el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.


1 Answers

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.

like image 107
jackwanders Avatar answered Oct 12 '22 21:10

jackwanders