使用 RequireJS 设置默认 API url 的主干集合
如何为 Backbone 中集合和模型的所有请求设置默认 url/服务器?
示例集合:
define([
'backbone',
'../models/communityModel'
], function(Backbone, CommunityModel){
return Backbone.Collection.extend({
url: '/communities', // localhost/communities should be api.local/communities
model: CommunityModel,
initialize: function () {
// something
}
});
});
我进行初始 AJAX 调用来获取我的设置,包括 API (api.local) 的 url。
如何重新路由请求而不将其传递给我的所有模型或对模型和集合中的 url 进行硬编码?
How can I set a default url/server for all my requests from collections and models in Backbone?
Example collection:
define([
'backbone',
'../models/communityModel'
], function(Backbone, CommunityModel){
return Backbone.Collection.extend({
url: '/communities', // localhost/communities should be api.local/communities
model: CommunityModel,
initialize: function () {
// something
}
});
});
I make an initial AJAX call to get my settings including the url of the API (api.local).
How can I reroute the requests without passing it to all my models or hardcoding the url in the models and collections?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的 url 接受一个字符串或一个函数。
通过您的设置 ajax 调用,您可以将其存储在正确的位置,
并从函数中获取它
以使用您的示例:
假设您的 ajax 调用将 URL 保存在
myApp.Settings.DefaultURL
remark 中
确保在设置之前触发该 url 时以某种方式捕获或处理该 url,如果您的初始 ajax 调用失败或需要时间,您的应用程序可能已经在没有设置设置的情况下启动,如果使用
模型.save()
此时,您需要处理这个问题。your url takes a string or a function.
with your settings ajax call you can store it in a proper location,
and go fetch that from the function
to use your example:
suppose your ajax call, saved the url in a
myApp.Settings.DefaultURL
remark
make sure this url is somehow caught or handled when it would be fired before your settings are set, if your initial ajax call fails or takes its time, your app might already be started without it's settings set, should one use a
model.save()
at that point, you would need to handle this.通过重写(但不是重写)
Backbone.sync
方法,您可以获得相同的结果,而无需向每个模型/集合添加相同的代码。然后在您的模型/集合中,您可以照常声明
url
(例如url: '/events
),不要忘记使用新的
来请求文件Backbone.sync 代码某处。
By over-riding (but not over-writing) the
Backbone.sync
method you can achieve the same result without having to add the same code to every single model/collection.Then in your model/collection you can just declare the
url
as usual (e.g.url: '/events
)Don't forget to require the file with the new
Backbone.sync
code somewhere.