Reputation: 1616
I'm just trying to refer to an iron router route by name in a helper, rather than hard coding the url. So when the user clicks on a button, they are redirected to the item route with the id from the data-id attribute of the button.
items.html
<button class="btn btn-default btn-xs pull-right" data-id={{_id}}>View</button>
items.js
Template.items.events({
'click button': function(e) {
// This works but is hard coding the path
Router.go("/item/" + ($(e.currentTarget).data('id')));
// This doesn't work but is there an alternative method of doing this
Router.go(pathFor('item' id=_id))
}
});
router.js
Router.route('/item/:_id', {
name: 'item'
});
I can of course use pathFor in a template like so:
<a href="{{pathFor 'item' id=_id}}">View</a>
Or specify a data attribute:
<button class="btn btn-default btn-xs pull-right" data-path={{pathFor 'item' id=_id}}>View</button>
But wondered if there is an alternative / neater way to do it? If not I might revert back to using tags.
Upvotes: 4
Views: 1991
Reputation: 351
You're in luck, this is actually quite simple (though not yet made explicit in the docs).
Given the route item
that takes an _id
:
Router.route('/item/:_id', {
name: 'item'
});
There are actually two options. Option 1:
Router.go('item', variableWithIdValue)
Or, if you have an object with a member variable/function that matches the route's parameter (in this case, _id
):
Router.go('item', itemInstance)
In the second case, Iron:Router notices that the passed parameter has a member variable/function that matches the parameter defined in the route's path, so it calls it instead of using the passed parameter itself.
EDIT: I should mention that you may also pass a hash, such as:
Router.go('item', {_id: variableWithIdValue})
This actually is described in the docs here:
https://github.com/EventedMind/iron-router/blob/devel/Guide.md#named-routes
Upvotes: 2
Reputation: 3043
First thing,
You don't need to use data-id
attrib in html, this._id will be available in click event
Second,for the Router.go
you can use Router.go("item",{_id:this._id});
Code
Template.items.events({
'click button': function(e) {
Router.go("item",{_id:this._id});
}
});
Refer to the docs here: https://github.com/EventedMind/iron-router/blob/devel/Guide.md#named-routes
Upvotes: 2