可以使用主干网.js动态/通配符子域路由



我正在构建一个系统,该系统将从url(variable1.domain.com/variable2)中提取2个变量。

我找不到任何文档显示如何使用骨干中的子域执行任何操作。Default_url只是作为 domain.com/api 传递。我确实找到了一个名为CORS(www.enable-cors.org)的东西,它可以支持跨域调用,但它没有提到动态域。

干甚至有可能这样的事情吗?如果没有,有谁知道余烬.js或其他类似骨干的系统是否具有此"功能"?

这当然是可能的,但不在 Backbone 的默认行为范围内。假设您的所有子域都使用相同的路由器代码,您可以破解可能如下所示的解决方案:

var Router = Backbone.Router.extend({
  routes: {
    '*variables': 'buildRoute'
  },
  subdomain: function() {
    // This is probably not the prettiest/best way to get the subdomain
    return window.location.hostname.split('.')[0];
  },
  buildRoute: function(variables) {
    // `variables` are all your hash variables
    // e.g., in the URL http://variable1.domain.com/#variable3=apples&variable4=oranges
    // `variables` here would be the string 'variable3=apples&variable4=oranges'
    // so you would have to parse that string into a JSON representation, but that's trivial
    // Once you have the JSON, you can do something like:
    myView.render(this.subdomain(), variablesJSON);
    // Your view's `render` function then has the subdomain and all the variables from the URL,
    // so it can use them appropriately.
  }
});

这种方法的一个重要警告是:它适用于自己导航到 URL 的用户,但当您的应用程序需要对 Router 执行navigate调用时,很快就会变得不稳定。主干将仅导航到URL的哈希部分,因此它不会包含子域。您可能需要启动一个自定义导航函数,该函数在执行其他任何操作之前设置window.location

显然,这可能不是Backbone适合的。我不确定 Ember 或其他任何东西是否具有此功能,但我会对此表示怀疑。子域名是指您网站的不同区域,因此您可能没有正确使用它们。

最新更新