如何生成与Backbone.js的型号标识 [英] How to generate model id's with Backbone.js

查看:115
本文介绍了如何生成与Backbone.js的型号标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设立的骨干同步机制,有点糊涂,其中生成的ID为模特。

当我创建一个新的模式,应该骨干网发电和设置ID,或者我应该实现一个ID生成的方法,或者是有某种机制在哪里PUT数据到服务器,该服务器产生id和返回模型中的id?


解决方案

  

    

或者是有某种机制在哪里PUT数据到服务器,该服务器产生的ID,并返回一个模型中的id?


  

类。当你调用模型的save方法,骨干进行POST XHR和应用程序服务器使用JSON包含一个ID应该响应。
你可以在这里看到一个例子:<一href=\"http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/\">http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/

从引用链接:

 后/ API /:事'做
  #解析的内容后身体被张贴,转换为字符串,插入
  #收集#thing并返回的ObjectId作为参考的字符串
  OID = DB.collection(PARAMS [:东西])。插入(JSON.parse(request.body.read.tos))
  {\\ID \\:\\#{oid.to_s} \\}
结束

如果您不知道红宝石记住什么被评为前最后pression自动由该方法返回。

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?

解决方案

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.

这篇关于如何生成与Backbone.js的型号标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆