2

I'm confused about send collection or model to the server.

This is my model:

var Person = Backbone.Model.extend({
    defaults : {},
    initialize : function() {}
});

and this is my collection:

var Usercollection = Backbone.Collection.extend({
    model : Person,
    url : 'https://api.parse.com/1/classes/_User/'
});

Now, if I would save a model on the server I have first to add in a collection and use save on model or first add in a collection and use save on collection? And least, I have to write an ajax call to post the collection or model in a server?

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96

3 Answers3

1

You should save your model to server.

Save a model: Call save() on model e.g.

    var user = new UserModel();    
    user.save({name: 'SJ', age:'35'}, {
      success: function (user) {
        // I get a model here with id
      }
    });

Read these links for more information.

I have given you the link of server side code to have a look at the APIs to make things more meaningful to you. Hope this helps!

Community
  • 1
  • 1
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • Good point: If you look at code written by Thomas, you will get it. Whenever we save a model to backend, either you can add the model to collection in the success handler or you should fetch the complete collection. So when you make a call to fetch the entire collection, it will read you Database and make a list of models and return the list. – Sachin Jain May 10 '13 at 18:34
  • In thomas's code, in success handler of user.save() he redirects to a new route and in that very route he fetches entire collection from server and renders again. So the newly added model gets added to collection itself. – Sachin Jain May 10 '13 at 18:35
0

Use collection.create();

http://backbonejs.org/#Collection-create

Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. ...

var Library = Backbone.Collection.extend({
  model: Book
});

var nypl = new Library;

var othello = nypl.create({
  title: "Othello",
  author: "William Shakespeare"
});
Scott Puleo
  • 3,684
  • 24
  • 23
0

If you want to add the model to the collection after the model is saved, you need to use .create on the collection , which fires the add event on the collection after it gets created..

this.collection.create(model.toJSON() , options);
Sushanth --
  • 55,259
  • 9
  • 66
  • 105