相对链接和backbone.js路由器
Relative links and backbone.js router
我使用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'
- Backbone.js路由器和Internet Explorer重定向问题
- Ember.js路由器,从视图获取路由器
- Backbone.js路由器混淆(pushState:true,尾部斜杠)
- Backbone.js路由器和后退按钮检查
- 相对链接和backbone.js路由器
- Durandal js路由器设置
- 针对浏览器的不同响应的Backbone.js路由器模式“;背面“;按钮或直接导航
- 在快速.js路由器函数中从 mongo 返回数据
- 如何在主干中显示视图.js(路由器.js中不显示警报)
- 主干.js路由器回调,用于在除 1 个特定 URL 段之外的所有 URL 段上触发
- 快速.js路由器中的自定义处理程序
- Express.js路由器中的正则表达式
- 如何让 Backbone.js 路由器在 CodeIgniter 中的默认值/索引(无 #tag 主题标签)上触发
- 骨干网.js路由器的严格参数匹配
- 骨干 JS - 路由器功能 - 调用视图
- 骨干网.js路由器动态第一参数
- backbone.js路由器-在后退按钮上运行不同的功能或检测后退按钮按下
- backbone.js路由器,具有多个操作
- Backbone.js路由器匹配可选参数
- 在Backbone.js路由器中定义一个基本url