Search code examples
javascriptmeteorroutesiron-router

Meteor, Iron:Router Passing Multiple Properties on Router.go


My dilemma is that I would like to pass multiple object properties to an iron:router route in Meteor. The reasoning is that I would like to pass it a property to name my url with and a property to find a collection item with. They are completely independent of each other and I can't use the url property because it is not a value in the collection item. This is what I have:

Template.items.events({
'click': function () {
    itemName = this.name.replace(/ /g,'')
    Router.go('itemDetails', {itemName: itemName})
    }
});

The problem is that although the Router handles this fine and sends me to the correct url, I cannot use itemName to find the collection item object that I am looking for (assume this is impossible).

Router.route('/items/:itemName', {
    name: 'itemDetails', 
    data: function() {return Items.findOne({name: this.params.itemName})}
});

The above Router configuration will not return anything because name != this.params.itemName for any object.

I've tried passing the this object, or creating objects with multiple properties, but iron:router won't have it.

Any help is appreciated, thanks.

Edit #1: To help explain the question further, my problem is the same as routing to a page that uses multiple id's in the URL. For example, how would I go about passing properties to iron:router to fill the :_id and :itemId properties?

Router.route('items/:_id/:_itemId', {
    name: 'detailDetails',
    data: function() {...}
});

Edit #2: What I would like to do specifically is pass two properties to iron:router and have one of them be appended to the URL, and the other be used in the data property of the route to return a collection item. Example:

....
    Router.go('itemDetails', {_id: itemBeingPassedId, itemName: nameToBeAppendedToURL})
....

Router.route('/items/:itemName', {
    name: 'itemDetails',
    data: function(){return Items.findOne(_id)
});

Whenever I try to do that, it says that _id is undefined. So basically, how can I pass a property to data without having it be a part of the URL and using this.params?


Solution

  • Is the question how to pass multiple parameters to Router.go? Just put all of them in the object for the second parameter:

    Router.go('itemDetails', {_id: 'foo', '_itemId': bar});
    

    Edit:

    Ok, if you want to pass arbitrary values to the url, you can use query paramters:

    Router.go('itemDetails', {itemName: 'foo'}, {query: 'id=bar'});
    

    The id will still be in the url though, it will look like this:

    http://example.com/items/foo?id=bar
    

    And you can retrieve it like this:

    Router.route('/items/:itemName', {
        name: 'itemDetails',
        data: function(){
            return {
                item: Items.findOne(this.params.query.id),
                itemName: this.params.itemName
            };
        }
    );