Nyx*_*nyx 2 html javascript jquery backbone.js
我在backbone.js中使用路由器功能并遇到了这个问题.这可能是一件微不足道的事情,但我似乎无法弄清楚这一点,也没有在谷歌上找到任何东西.
问题:页面上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();
Run Code Online (Sandbox Code Playgroud)
当我设置标签的href属性时,结果的链接是.a<a href="profile">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>
Run Code Online (Sandbox Code Playgroud)
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;
}
});
Run Code Online (Sandbox Code Playgroud)
或者,正如我有时感觉到的那样:
模板:
<script type="text/template" id="template-element">
<h1><%= title %></h1>
<a class="profile" href="#replace_with_real_url">profile</a>
</script>
Run Code Online (Sandbox Code Playgroud)
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;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4758 次 |
| 最近记录: |