How to generate model id's with Backbone.js

前端 未结 3 561
梦谈多话
梦谈多话 2021-01-30 23:22

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 an

3条回答
  •  天涯浪人
    2021-01-31 00:13

    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.

提交回复
热议问题