jQuery 了解 Backbone.js REST 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18504235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understand Backbone.js REST calls
提问by testndtv
I am trying to understand the Backbone.js sync method and was going through the documentation on http://backbonejs.org/#Sync
我正在尝试了解 Backbone.js 同步方法,并且正在浏览http://backbonejs.org/#Sync上的文档
It says
它说
The default sync handler maps CRUD to REST like so:
create → POST /collection
read → GET /collection[/id]
update → PUT /collection/id
delete → DELETE /collection/id
Now since I have always been in front-end development and new to Backbone, I find the above hard to understand...I have never used REST or any other server-side protocols...
现在因为我一直在前端开发和 Backbone 新手,我发现上面的内容很难理解......我从未使用过 REST 或任何其他服务器端协议......
Could you please explain the same in simple terms (like how the REST maps when we use Backbone.sync) Any very simple example would be highly useful...
你能不能用简单的术语解释一下(比如当我们使用 Backbone.sync 时 REST 是如何映射的)任何非常简单的例子都会非常有用......
回答by ZachRabbit
If you don't mind, I'm going to start with clearing up some wording. REST is not a protocol in itself, it's simply a way of using the HTTP protocol. The REST style is especially useful for APIs, as I hope you'll see. When an API conforms to that style, it is said to be "RESTful". If the API you're working with isn't RESTful, you'll have to make a lot of changes to Backbone.sync in order to get it to work. So hopefully it is! :)
如果你不介意,我将开始清理一些措辞。REST 本身并不是一种协议,它只是一种使用 HTTP 协议的方式。REST 风格对于 API 尤其有用,我希望您会看到。当 API 符合该风格时,它被称为“RESTful”。如果您使用的 API 不是 RESTful,您必须对 Backbone.sync 进行大量更改才能使其正常工作。所以希望它是!:)
The HTTP Protocol
HTTP 协议
I like examples, so here is an HTTP request to get the HTML for this page:
我喜欢例子,所以这里有一个 HTTP 请求来获取这个页面的 HTML:
GET /questions/18504235/understand-backbone-js-rest-calls HTTP/1.1
Host: stackoverflow.com
[Optional] If you have ever played with command line or terminal, try running the command telnet stackoverflow.com 80
and pasting in the above, followed by pressing enter a couple of times. Voila! HTML in all of it's glory.
[可选] 如果您曾经玩过命令行或终端,请尝试运行命令telnet stackoverflow.com 80
并粘贴上面的内容,然后按几次 Enter。瞧!HTML 尽显荣耀。
In this example...
在这个例子中...
GET
is the method./questions/18504235/understand-backbone-js-rest-calls
is the path.HTTP/1.1
is the protocol.Host: stackoverflow.com
is an example of a header.
GET
是方法。/questions/18504235/understand-backbone-js-rest-calls
是路径。HTTP/1.1
是协议。Host: stackoverflow.com
是header 的一个例子。
Your browser does approximately the same, just with more headers, in order to get the HTML for this page. Cool, huh?
您的浏览器执行大致相同的操作,只是增加了更多标题,以便获取此页面的 HTML。很酷吧?
Since you work in front end, you've probably seen the form tag many times. Here's an example of one:
由于您在前端工作,您可能已经多次看到表单标签。这是一个例子:
<form action="/login" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Log In" />
</form>
When you submit this form along with appropriate data, your browser sends a request that looks something like this:
当您提交此表单以及适当的数据时,您的浏览器会发送一个类似于以下内容的请求:
POST /login HTTP/1.1
Host: stackoverflow.com
username=testndtv&password=zachrabbitisawesome123&submit=Log%20In
There are three differences between the previous example and this one.
上一个示例与本示例之间存在三个不同之处。
- The methodis now
POST
. - The pathis now
/login
. - There is an extra line, called the body.
- 该方法是现在
POST
。 - 该路径现在
/login
。 - 有一条额外的线,称为body。
While there are a bunch of other methods, the ones used in RESTful applications are POST
, GET
, PUT
, and DELETE
. This tells the server what type of action it's supposed to take with the data, without having to have different paths for everything.
虽然有一堆的其他方法,在RESTful应用程序所使用的那些是POST
,GET
,PUT
,和DELETE
。这会告诉服务器它应该对数据采取什么类型的操作,而不必为所有内容设置不同的路径。
Back to Backbone
回到主干
So hopefully now you understand a bit more about how HTTP works. But how does this relate to Backbone? Let's find out!
所以希望现在您对 HTTP 的工作原理有了更多的了解。但这与 Backbone 有何关系?让我们一探究竟吧!
Here's a small chunk of code you might find in a Backbone application.
这是您可能会在 Backbone 应用程序中找到的一小段代码。
var BookModel = Backbone.Model.extend({
urlRoot: '/books'
});
var BookCollection = Backbone.Collection.extend({
model: BookModel
, url: '/books'
});
Create (POST)
创建(POST)
Since we're using a RESTful API, that's all the information Backbone needs to be able to create, read, update, and delete all of our book information! Let's start by making a new book. The following code should suffice:
由于我们使用的是 RESTful API,这就是 Backbone 创建、读取、更新和删除我们所有图书信息所需的所有信息!让我们从制作一本新书开始。以下代码应该足够了:
var brandNewBook = new BookModel({ title: '1984', author: 'George Orwel' });
brandNewBook.save();
Backbone realizes you're trying to createa new book, and knows from the information it's been given to make the following request:
Backbone 意识到您正在尝试创建一本新书,并从所提供的信息中知道提出以下请求:
POST /books HTTP/1.1
Host: example.com
{"title":"1984","author":"George Orwel"}
Read (GET)
读取 (GET)
See how easy that was? But we want to get that information back at some point. Let's say we ran new BookCollection().fetch()
. Backbone would understand that you're trying to reada collectionof books, and it would make the following request:
看到那是多么容易吗?但我们想在某个时候取回这些信息。假设我们跑了new BookCollection().fetch()
。骨干会明白,你想读一个收集的书籍,并会提出以下要求:
GET /books HTTP/1.1
Host: example.com
BAM. That easy. But say we only wanted the information for one book. Let's say book #42. Say we ran new BookModel({ id: 42 }).fetch()
. Backbone sees you're trying to reada singlebook:
营商事工。这么容易。但是假设我们只想要一本书的信息。假设第 42 本书。说我们跑了new BookModel({ id: 42 }).fetch()
。主干看到你想读一个单一的书:
GET /books/42 HTTP/1.1
Host: example.com
Update (PUT)
更新 (PUT)
Oh darn, I just realized I spelled Mr. Orwell's name wrong. Easy to fix!
哦该死,我才发现我拼错了奥威尔先生的名字。易于修复!
brandNewBook.set('author', 'George Orwell');
brandNewBook.save();
Backbone is smart enough to know that despite being called brandNewBook
, it's already been saved. So it updatesthe book:
Backbone 足够聪明,知道尽管被调用brandNewBook
,但它已经被保存了。所以它更新了本书:
PUT /books/84 HTTP/1.1
Host: example.com
{"title":"1984","author":"George Orwell"}
Delete (DELETE)
删除(删除)
Finally, you realize that the government is tracking your every move, and you need to bury the fact that you have read 1984. It's probably too late, but it never hurts to try. So you run brandNewBook.destroy()
, and Backbone becomes sentient and realizes your dangerdeletesthe book with the following request:
最后,你意识到政府正在跟踪你的一举一动,你需要掩饰你读过 1984 的事实。现在可能已经太晚了,但尝试永远不会有什么坏处。所以你运行brandNewBook.destroy()
,Backbone变得有知觉并意识到你的危险,并通过以下请求删除了这本书:
DELETE /books/84 HTTP/1.1
Host: example.com
And it's gone.
它不见了。
Other Useful Tidbits
其他有用的花絮
While we've talked a lot about what we're sending TO the server, we should probably also take a look at what we're getting back. Let's return to our collection of books. If you remember, we made a GET
request to /books
. In theory, we should get back something like this:
虽然我们已经讨论了很多关于我们发送到服务器的内容,但我们可能还应该看看我们返回的内容。让我们回到我们的书籍收藏。如果您还记得,我们向 提出了一个GET
请求/books
。理论上,我们应该返回这样的东西:
[
{"id":42,"author":"Douglas Adams","title":"The Hitchhiker's Guide to the Galaxy"}
, {"id":3,"author":"J. R. R. Tolkien","title":"The Lord of the Rings: The Fellowship of the Ring"}
]
Nothing too scary. And even better, Backbone knows how to handle this out of the box. But what if we changed it a bit? Instead of id
being the identifying field, it was bookId
?
没什么太可怕的。更好的是,Backbone 知道如何开箱即用地处理这个问题。但是如果我们稍微改变一下呢?它不是id
识别字段,而是bookId
?
[
{"bookId":42,"author":"Douglas Adams","title":"The Hitchhiker's Guide to the Galaxy"}
, {"bookId":3,"author":"J. R. R. Tolkien","title":"The Lord of the Rings: The Fellowship of the Ring"}
]
Backbone gets that every API is a bit different, and it's okay with that. All you have to do is let it know the idAttribute
, like so:
Backbone 认为每个 API 都有点不同,这没关系。你所要做的就是让它知道idAttribute
,就像这样:
var BookModel = Backbone.Model.extend({
urlRoot: '/books'
, idAttribute: 'bookId'
});
You only have to add that information to the model, since the collection checks the model anyway. So just like that, Backbone understands your API! Even if I don't...
您只需将该信息添加到模型中,因为该集合无论如何都会检查模型。就这样,Backbone 了解您的 API!就算我不...
The downside of this is that you have to remember to use bookId
in certain cases. For example, where we previously used new BookModel({ id: 42 }).fetch()
to load the data about a single book, we would now have to use new BookModel({ bookId: 42 }).fetch()
.
这样做的缺点是您必须记住bookId
在某些情况下使用。例如,我们以前用来new BookModel({ id: 42 }).fetch()
加载关于一本书的数据,现在我们必须使用new BookModel({ bookId: 42 }).fetch()
.
Hopefully you've found this response informative, and not too unbearably dull. I realize that for many, HTTP protocol and RESTful architecture aren't the most exhilarating subjects, so I tried to spice it up a bit. I may regret that when I read all of this back at a later point, but it's 2AM here, so I'm gonna go ahead and submit this anyway.
希望您已经发现此回复内容丰富,并且不会太乏味。我意识到对很多人来说,HTTP 协议和 RESTful 架构并不是最令人振奋的主题,所以我试图给它加点趣味。当我稍后阅读所有这些内容时,我可能会感到遗憾,但现在是凌晨 2 点,所以无论如何我都会继续提交。
回答by GijsjanB
Assuming you understand ajax calls (POST, GET, etc to '/collection', etc).
假设您了解 ajax 调用(POST、GET 等到“/collection”等)。
Backbone uses sync to route some Models and Collections methods to REST calls.
Backbone 使用同步将一些模型和集合方法路由到 REST 调用。
model/collection.fetch() => GET
model.save() => POST (isNew())
model.save() => PUT (!isNew())
model.destroy() => DELETE
collection.create()
calls model.save() (isNew()) => POST
collection.create()
电话 model.save() (isNew()) => POST
If you pass the url (/collection) you want to use to a model/collection, Backbone will take care of the calls.
如果您将要使用的 url (/collection) 传递给模型/集合,Backbone 将处理调用。