使用 RequireJS 的 Backbone 集合设置默认 API url [英] Backbone collection setting default API url using RequireJS

查看:19
本文介绍了使用 RequireJS 的 Backbone 集合设置默认 API url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为来自 Backbone 中的集合和模型的所有请求设置默认 URL/服务器?

How can I set a default url/server for all my requests from collections and models in Backbone?

示例集合:

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 的 url (api.local).

I make an initial AJAX call to get my settings including the url of the API (api.local).

如何在不将请求传递给我的所有模型或在模型和集合中硬编码 url 的情况下重新路由请求?

How can I reroute the requests without passing it to all my models or hardcoding the url in the models and collections?

推荐答案

你的 url 需要一个字符串或一个函数.

your url takes a string or a function.

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

with your settings ajax call you can store it in a proper location, and go fetch that from the function

使用您的示例:假设您的 ajax 调用,将 url 保存在 myApp.Settings.DefaultURL

to use your example: suppose your ajax call, saved the url in a 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
        }
    });
});

备注确保在设置设置之前以某种方式捕获或处理此 url,如果您的初始 ajax 调用失败或花费时间,则您的应用程序可能已经在没有设置设置的情况下启动,如果使用 模型.save() 此时,您需要处理此问题.

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.

这篇关于使用 RequireJS 的 Backbone 集合设置默认 API url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆