Setting a global REST root url in a Backbone.js ap

2019-04-07 07:45发布

In backbone.js, you have to set the rooturl of every model manually. Is there a way we can set this in a single location once and all models will use it?

For eg. api.site.com will be the REST service, but for testing purpose, it may be at localhost:1000 I need to be able to change the root url of the service easily and not have them all over the place in the many models that exist in the application.

标签: backbone.js
7条回答
趁早两清
2楼-- · 2019-04-07 08:41

What I understand is :

You have several models: model1 and model2

The root URL can be either http://api.site.com or http://localhost:8080 depending on whether you are working locally or externally. And someday it could be http://api.anothersite.com

I would do somthing like this then :

// Global var before any other JS code, you comment line depending on which one applies
var ROOT = 'http://api.site.com'
// var ROOT = 'http://localhost:8080'

var Model1 = Backbone.Model.extend({
urlRoot: ROOT+'/model1',
...
});

var Model2 = Backbone.Model.extend({
urlRoot: ROOT+'/model2',
...
});

But be careful with this, you may forget to switch from one url to the other one when commiting. Better is to handle relative paths if they'd apply.

查看更多
登录 后发表回答