Reputation: 63619
I'm using the router function in backbone.js and came across this problem. This may be a trivial thing, but I cant seem to figure this out nor find anything on Google.
Problem: On the page http://www.mydomain.com/user/1
there is a link. This link should link to http://www.mydomain.com/user/1/profile
.
Of course if I use <a href="1/profile">
I get what I am looking for, but 1
is a dynamically generated value. How then should my router define the routes? I believe its not a wise choice to hardcode the number 1
into the routes.
//Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'profile',
'profile': 'profile'
},
profile: function() {
}
});
var app = new AppRouter();
Backbone.history.start();
When I set the href
attribute of the a
tag like <a href="profile">
, the link that results is http://www.mydomain.com/user/profile
.
For <a href="./profile">
I get http://www.mydomain.com/user/profile
.
For <a href="/profile">
I get http://www.mydomain.com/profile
.
For <a href="profile/">
I get http://www.mydomain.com/profile/
.
Why is the 1
missing, and how can I keep it to achieve what I want?
Upvotes: 2
Views: 4819
Reputation: 38772
You can't define this dynamic URLs directly in the HTML, you have to create them into your Views.
For example:
template:
<script type="text/template" id="template-element">
<h1><%= title %></h1>
<a class="profile" href="<%= url_profile %>">profile</a>
</script>
js code:
// 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;
}
});
Or, as I do sometimes when I feel in the way:
template:
<script type="text/template" id="template-element">
<h1><%= title %></h1>
<a class="profile" href="#replace_with_real_url">profile</a>
</script>
js code:
// 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;
}
});
Upvotes: 5
Reputation: 12235
as you can see in http://backbonejs.org/#Router, you can use parameters in your routes, as in '/user/:id/profile'
Upvotes: -1