我有一个 html 包装应用程序,从 ipad 文件存储加载所有 js、css 和图像。因此,UIWebView 加载了不同的基本 href。
主干数据的加载应正常发送至服务器。有没有办法在主干中设置基本 href - 所以主干与服务器相关,而不是文件存储?也许以全局的方式?
最佳答案
一种选择是覆盖您想要“重新建立基础”的每个集合或模型类型的 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
}
});
如果您有很多模型和集合类型,并且希望重新设置它们的所有 url,那么覆盖 Backbone.sync(由所有模型和集合 CRUD 操作调用)可能会更好。在 url 被注入(inject) $.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);
}
我还没有测试过确切的代码,但我认为它(或接近的代码)应该可以工作。
关于javascript - 如何在主干中设置自定义基本href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925105/