如何在骨干网中设置自定义基础href?

0 javascript backbone.js

我有一个html包装器应用程序从ipad文件存储加载所有js,css和图像.因此,UIWebView加载了不同的基本href.

骨干数据的加载应该正常进入服务器.有没有办法在骨干网中设置基本href - 因此骨干对服务器而言是实际的,而不是文件存储?也许以全球方式?

hea*_*ide 6

一种选择是覆盖您想要"重新基础"的每个Collection或Model类型的url或urlRoot属性,如:

Article = Backbone.Model.extend({
  url: function() {
    return "http://myapiserver.com/articles/" + this.id;
    // Or slightly better, use some global for the base url and build from that
  }
});
Run Code Online (Sandbox Code Playgroud)

如果您有很多模型和集合类型,并且您希望它们的所有URL都重新基础,那么通过重写Backbone.sync(由所有模型和集合CRUD操作调用)来覆盖url在被泵入$ .ajax()之前.你可以这样做:

// We'll call the "standard" Backbone.sync to do the real work, so grab a
// reference to it.
var oldSync = Backbone.sync;

Backbone.sync = function(method, model, options) {
    var url = _.isFunction(model.url) ? model.url() : model.url;

    if (url) {  // If no url, don't override, let Backbone.sync do its normal fail
        options = options || {};
        options.url = "http://myapiserver.com" + url;
    }

    // Let normal Backbone.sync do its thing
    return oldSync.call(this, method, model, options);
}
Run Code Online (Sandbox Code Playgroud)

我没有测试过那些确切的代码,但我认为它(或接近的东西)应该可行.