我有一个名为 TodoModel
的模型和一个名为 Todos
的集合。我用来获取数据的 url 是一个外部 api,因此我将我的集合的 url 函数覆盖为
url:function(){
return "http://abc.com/data"
}
当我从我的 View 中编写 Todos.fetch()
时,这工作正常。
现在,我想传递一些参数,例如 http://abc.com/data/[id]
。
在点击每个元素时,将有一个具有不同 ID 的不同 API 调用。例如:
http://abc.com/data/123
http://abc.com/data/234
我如何实现这一目标?
我应该将模型的 url 设置为这个外部 url 吗?我该如何解决这个问题?
最佳答案
如果您在集合中的模型上设置 ID,同步将自动进行。例如,如果您有一个 ID 为 123
且 save()
的 Todo
模型它将 POST
到 http://abc.com/data/123
。
Models within the collection will use url to construct URLs of their own.
来自Model.url docs :
Generates URLs of the form:
"/[collection.url]/[id]"
, falling back to"/[urlRoot]/id"
if the model is not part of a collection.
参见 Backbone's sync documentation查看 HTTP 方法如何映射到集合中模型上的各种 URL。
关于javascript - 使用 backbone.js 在外部 api 上获取、放置和删除请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709723/