相对链接和backbone.js路由器

Relative links and backbone.js router

本文关键字:js 路由器 backbone 链接 相对      更新时间:2024-04-23

我使用backbone.js中的router函数时遇到了这个问题。这可能是一件微不足道的事情,但我似乎无法理解,也无法在谷歌上找到任何东西。

问题:http://www.mydomain.com/user/1页面上有一个链接。此链接应链接到http://www.mydomain.com/user/1/profile

当然,如果我使用<a href="1/profile">,我会得到我想要的,但1是一个动态生成的值。那么我的路由器应该如何定义路由?我认为将数字1硬编码到路由中不是一个明智的选择。

//Router
var AppRouter = Backbone.Router.extend({
    routes: {
        '': 'profile',
        'profile': 'profile'
    },
    profile: function() {
    }
});
var app = new AppRouter();
Backbone.history.start();

当我像<a href="profile">一样设置a标签的href属性时,得到的链接是http://www.mydomain.com/user/profile

对于<a href="./profile">,我得到http://www.mydomain.com/user/profile

对于<a href="/profile">,我得到http://www.mydomain.com/profile

对于<a href="profile/">,我得到http://www.mydomain.com/profile/

为什么1不见了,我该如何保留它来实现我想要的?

您不能直接在HTML中定义这个动态URL,您必须在视图中创建它们。

例如:

模板:

<script type="text/template" id="template-element">
  <h1><%= title %></h1>
  <a class="profile" href="<%= url_profile %>">profile</a>
</script>

js代码:

// code simplified and no tested
var Element = Backbone.Model.extend({
  initialize: function(){
    this.set( "url_profile", this.url() + "/profile" );
  }
});
var ElementView = Backbone.View.extend({
  template: _.template( $("#template-element").html() ),
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
    return this;
  }
});

或者,就像我有时遇到麻烦时所做的那样:

模板:

<script type="text/template" id="template-element">
  <h1><%= title %></h1>
  <a class="profile" href="#replace_with_real_url">profile</a>
</script>

js代码:

// no Element.url_profile attribute needed:
var ElementView = Backbone.View.extend({
  template: _.template( $("#template-element").html() ),
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
    this.$el.find( ".profile" ).attr( "href", "/user/" + this.model.id + "/profile" );
    return this;
  }
});

如中所示http://backbonejs.org/#Router,您可以在路线中使用参数,如'/user/:id/profile'