Search code examples
javascriptmeteoriron-router

Meteor router and url paramaters


I'm having some trouble trying to use the URL parameters in meteor with iron:router.

On the home page if my app, I display a thread of posts. But I want to allow people to select a single thread by specifying its ID in the url. Like that, when someone click on a link to a specific thread like myapp/the_asked_id, he only see the data related to the thread. Otherwise, he see all threads.

I think it would be something where I get the data from the url like in PHP, and then check for the value / existence of this parameter : if it exists / has a correct value, I display the thread, otherwise I display all of them.

Here is what I've tried so far :

HTML link :

<a href="#" class="dropdown-toggle green-link" data-toggle="dropdown" title="Notifications" data-target="{{link}}">the link</a>

with {{link}} to be the _id from my collection to identify the required thread / doc to display.

Js link event :

'click .talkLink' : function(event, template){
      if($(event.target).hasClass('talkLink'))
      {
        console.log(event.target.dataset.target);
        console.log(event.currentTarget);
      }
      else {
        console.log(event.currentTarget);
      }
      Router.go('/', {_id: event.target.dataset.target});
    },

Router :

this.route('home', {
      path: '/:_id?',
      data: {
        threadId: (this.params._id || "")
      }
    });

But I can't get it working, as it currently always display me the not found template...

Could someone explain me what is going wrong and how I should proceed ?

Thank you,

David


Solution

  • A few suggestions:

    this.route('home', {
        path: '/:_id',
        data: function() {
            // assuming you have a collection called "Threads"
            return Threads.findOne(this.params._id);
        }
    });
    
    1. You need a template called 'home'. It's data context will be the return of the data callback
    2. You do not need to place a ? in the path
    3. data is a callback, in which you can access this.params within to find the correct document.