问题描述
如果我有一个名为书籍的模式,并命名为图书馆,如下定义的集合:
If I have a model named "Book" and a collection named "Library" defined as below:
图书
app.Book = Backbone.Model.extend({
defaults: {
title: 'No title',
author: 'Unknown'
}
});
图书馆
app.Library = Backbone.Collection.extend({
model: app.Book,
url: '/api/books'
});
当我称之为 BookInstance.save()
它是如何拿出来使用的URL?它从集合派生呢?
When I call BookInstance.save()
how does it come up with the URL to use? Does it derive it from the collection?
在 Backbone.model
有2个选项:网址
和 urlRoot
。什么是它们之间的用途和区别?
In Backbone.model
there are 2 options: url
and urlRoot
. What is the purpose and difference between these?
在 Backbone.collection
,有一个参数网址
。这是始终RESTful API实GET请求?
In Backbone.collection
, there is a single parameter url
. Is this always the GET request for the RESTFUL api?
推荐答案
基本上,有3种可能性,构建一个模型的网址:
Basically, there are 3 possibilities to construct a model's url:
-
如果集合中存在的模型对象则其
网址
方法将返回collection.url 和
model.id
:[collection.url] / [ID]
如果你不想使用集合内的模型,那么
片段,从而产生以下模式: model.urlRoot
的值可以用来代替<$ C $的C> collection.url [urlRoot] / [ID]
If you don't want to use a model inside the collection, then model.urlRoot
's value can be used instead of the collection.url
fragment, resulting in the following pattern: [urlRoot]/[id]
.
最后,如果你不打算坚持给定类型的更多的一个模型服务器或将被定义在他们创建的每个模型的网址,就可以直接分配一个值 model.url
。
Finally, if you're NOT planning to persist more that one model of a given type to the server or will be defining URLs for each model upon their creation, you can directly assign a value to model.url
.
集合只发送GET请求 - 让模型的JSON数据的数组。为了节省,删除和更新,个别型号的保存()
(POST / PUT / PATCH)和的destroy()
(DELETE)使用方法。
Collections send only GET requests — to get an array of models' JSON data. For saving, removing, and updating, the individual model's save()
(POST/PUT/PATCH) and destroy()
(DELETE) methods are used.
,这应有助于您:
Here's the source code of Backbone.Model.url
, which should help you:
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
var id = this.get(this.idAttribute);
return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
}
这篇关于骨干JS模型和收藏的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!