Search code examples
backbone.js

How to generate model id's with Backbone.js


I am setting up the backbone sync mechanism and am a bit confused where to generate the id's for the models.

When I create a new model, should backbone be generating and setting the id, or am i supposed to implement an id generation method, or is there some sort of mechanism where I "PUT" the data to the server, which generates the id and returns a model with the id?


Solution

  • or is there some sort of mechanism where I "PUT" the data to the server, which generates the id and returns a model with the id?

    Kind of. When you call the save method of your model, backbone make a POST XHR and your application server should respond with JSON contains an id. You can see an example here: http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/

    Quoting from the link:

    post '/api/:thing' do 
      # parse the post body of the content being posted, convert to a string, insert into 
      # the collection #thing and return the ObjectId as a string for reference 
      oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.tos)) 
      "{\"id\": \"#{oid.to_s}\"}" 
    end
    

    If you don't know Ruby keep in mind what the last expression that is evaluated is automatically returned by the method.