Global model base url and optional automapping

可紊 提交于 2019-12-25 03:42:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!