【问题标题】:possible to use backbone.js with dynamic/wildcard subdomain routing?可以将backbone.js 与动态/通配符子域路由一起使用吗?
【发布时间】:2012-04-11 17:50:53
【问题描述】:
我正在构建一个系统,该系统将从 url (variable1.domain.com/variable2) 中提取 2 个变量。
我找不到任何说明如何对骨干网中的子域执行任何操作的文档。 Default_url 只是作为 domain.com/api 传递的。我确实找到了一个名为 CORS (www.enable-cors.org) 的东西,它支持跨域调用,但它没有说明动态域。
这样的事情甚至可能与骨干?如果没有,有谁知道 ember.js 或其他类似主干的系统是否有这个“功能”?
【问题讨论】:
标签:
javascript
ember.js
backbone.js
url-routing
【解决方案1】:
这当然是可能的,但不在 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 调用时,它很快就会变得不稳定。 Backbone 将仅导航到 URL 的哈希部分,因此它不会包含子域。在执行其他任何操作之前,您可能必须启动一个设置 window.location 的自定义导航功能。
显然,这可能不是 Backbone 非常适合的事情。我不确定 Ember 或其他任何东西是否具有此功能,但我会怀疑。子域是您网站的不同区域,因此您可能没有正确使用它们。