问题
Is there a way to set a global api_root
attribute instead of repeating the declaration over and over in the codebase?
So instead of:
var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: {
name: '',
email: ''
}
});
var user = new UserModel();
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
});
I could have set an app-wide attribute like:
app.api_root = 'https://api.ltmo.com/';
And then just map according to convention:
var UserModel = Backbone.Model.extend({ // maps to https://api.ltmo.com/users/
defaults: {
name: '',
email: ''
}
});
var user = new UserModel();
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
});
回答1:
you could solve this on the jQuery level with ajaxprefilter:
$.ajaxPrefilter(function(options) {
options.url = 'https://api.ltmo.com/' + options.url;
});
来源:https://stackoverflow.com/questions/30585563/global-model-base-url-and-optional-automapping