如何使用Backbone.js生成模型ID

Nip*_*rus 21 backbone.js

我正在设置骨干同步机制,并且有点困惑在哪里为模型生成id.

当我创建一个新模型时,主干应该生成并设置id,还是我应该实现一个id生成方法,或者是否存在某种机制,我将数据"输出"到服务器,生成id和返回一个带有id的模型?

jmk*_*142 56

我提供了第二个答案来简化您需要学习的代码,以获得您正在思考的要点 - 从模型到服务器的实际轮次以及ID如何发挥作用.

假设你定义一个模型 - 让我们去侏罗纪公园吧.

// Define your model
var Dinosaur = Backbone.Model.extend({
    defaults: {
        cavemanEater: undefined    // Has one property, nom nom or not.
    },
    urlRoot: 'dino'               // This urlRoot is where model can be saved or retrieved
});

var tRex = new Dinosaur({'cavemanEater':true});
Run Code Online (Sandbox Code Playgroud)

你现在已经实例化了一个肉食者的恐龙.怒吼.

console.log(tRex);
Run Code Online (Sandbox Code Playgroud)

您应该注意的是,在tRex的属性中,您的模型没有id.相反,您将看到一个cID,您可以将其视为Backbone自动分配给您的模型的临时ID.当模型没有id时,它被认为是新的.持久化模型(数据库或本地存储)的概念允许您在创建它之后返回该资源并执行诸如保存(PUT)或销毁(DELETE)之类的操作.如果您无法直接指向它,那么很难找到该资源!为了找到该资源,您的模型需要一个id,这是目前没有的.

因此,正如上面的答案所解释的那样,为您的数据库(或localstorage或其他解决方案)提供Backbone资源ID.大多数情况下,这来自资源ID本身,也就是 - 某些表中模型的主键ID.

在我的设置中,我使用PHP和mySQL.我会有一个名为恐龙的表,每一行都是我的恐龙模型的持久表示.所以我有一个id列(唯一的自动递增int)和cavemanEater(bool).

数据通信流程就是这样发生的.

  1. 您创建一个模型.
  2. 该模型是新的,因此它只有一个cID - 没有正确的ID.
  3. 您保存模型.
  4. 模型的json表示是SENT到您的服务器(POST)
  5. 您的服务器将其保存到表中并为其提供资源ID.
  6. 您的服务器SENDS返回数据的json表示{id:uniqueID}
  7. Backbone使用id接收这个json表示
  8. Backbone使用id自动更新您的模型.

这是带注释的代码的样子.

客户:

tRex.save();
// {'cavemanEater':true} is sent to my server
// It uses the urlRoot 'dino' as the URL to send. e.g. http://www.example.com/dino
Run Code Online (Sandbox Code Playgroud)

服务器:

// Is setup to accept POST requests on this specific ROUTE '/dino'
// Server parses the json into something it can work with, e.g. an associative array
// Server saves the data to the database. Our data has a new primary id of 1.
// Data is now persisted, and we use this state to get the new id of this dino.

$dinoArray = array('id'=>1, 'cavemanEater'=>true);
$dinoJSON = json_encode($dinoArray);

// Server does something to send $dinoJSON back.
Run Code Online (Sandbox Code Playgroud)

客户:

// If successful, receives this json with id and updates your model.
Run Code Online (Sandbox Code Playgroud)

现在你的tRex有一个id = 1.或者我应该说......

tRex.toJSON();
// RETURNS {'id':'1', 'cavemanEater':'true'}
Run Code Online (Sandbox Code Playgroud)

恭喜.如果你这样做tRex.isNew(),它将返回false.

骨干很聪明.它知道POST已经拥有资源ID的新模型和PUT模型.

下次你这样做:

tRex.save();
Run Code Online (Sandbox Code Playgroud)

Backbone将向以下URL发出PUT请求.

http://www.example.com/dino/1

这是默认行为.但你会注意到的是,URL与保存不同.在服务器上,您需要一个接受/ dino /:id而不是/ dino的路由

默认情况下,它将为您的模型使用/ urlRoot /:id路由模式,除非您另外调整它.

不幸的是,恐龙灭绝了.

tRex.destroy();
Run Code Online (Sandbox Code Playgroud)

这会打电话......你能猜到吗?是的.删除/ dino/1的请求.

您的服务器必须区分对不同路由的不同请求才能使Backbone工作.有几种服务器端技术可以做到这一点.

如果您使用Ruby,有人会提到Sinatra.就像我说的,我使用PHP而且我使用SLIM PHP Framework.它的灵感来自Sinatra所以它很相似,我喜欢它.作者写了一些干净的代码.然而,这些RESTful服务器实现如何工作超出了本讨论的范围.

我认为这是新的Backbone数据的基本完整旅行,没有id,跨越互联网到你生成的服务器,并发送回资源​​id,让你的模型永远幸福地生活.(或者destroy()......)

我不知道这对你来说是否太初学,但希望它会帮助遇到这个问题的其他人.使用Backbone非常有趣.

其他类似的答案: 如何保存Backbone JS模型数据

  • 顺便说一下,您实际上可以手动将ID分配给模型.`someModel.set('id',777);`但为什么你想这样做是超出我的.:-) (3认同)
  • +1精美解释.救了我输入它的努力:D (2认同)

the*_*heo 9

或者是否存在某种机制,我将数据"输出"到服务器,生成id并返回带有id的模型?

的种类.当您调用模型的save方法时,backbone会生成POST XHR,而您的应用程序服务器应该使用包含id的JSON进行响应.你可以在这里看到一个例子:http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/

引用链接:

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
Run Code Online (Sandbox Code Playgroud)

如果您不知道Ruby,请记住该方法会自动返回所评估的最后一个表达式.