使用RequireJS骨干采集设置默认值API网址 [英] Backbone collection setting default API url using RequireJS

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

问题描述

如何设置一个默认的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(api.local)的URL。

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?

推荐答案

您需要的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

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调用失败或需要它的时候,你的应用程序可能已经没有它的设置中设置开始,应在使用 model.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骨干采集设置默认值API网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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