Backbone集合使用RequireJS设置默认API URL

Rie*_*bel 1 javascript api model-view-controller requirejs backbone.js

如何为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
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我进行初始的AJAX调用以获取我的设置,包括API的URL(api.local).

如何重新路由请求而不将其传递给我的所有模型或硬编码模型和集合中的URL?

San*_*der 5

你的网址采用字符串或函数.

使用您的设置ajax调用,您可以将其存储在适当的位置,然后从该函数中获取它

使用你的例子:假设你的ajax调用,保存了一个url myApp.Settings.DefaultURL

define([
    'backbone',
    '../models/communityModel'
], function(Backbone, CommunityModel){
    return Backbone.Collection.extend({
        url: function(){
            return myApp.Settings.DefaultURL + '/communities';
        }, 
        model: CommunityModel,
        initialize: function () {
            // something
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

注释 确保在设置设置之前触发或处理此URL时,如果您的初始ajax调用失败或花费时间,您的应用可能已经启动而没有设置,如果model.save()在此时使用了,你需要处理这个.