Search code examples
meteoriron-router

Router.go is not working


I have a meteor app. I built the layout and the application using Material Design Lite by google. Following is my navigation:

navigation html

<template name="nav">
    <nav class="mdl-navigation mdl-layout--large-screen-only">
        <a class="mdl-navigation__link" href="" id="home">Home</a>
        <a class="mdl-navigation__link" href="" id="my-pictures">My Pictures</a>
    </nav>
</template>

router file

passIfLoggedIn = ->
    if not Meteor.user()
        @render 'login'
    else
        @next()

Router.route '/home',
    waitOn: -> Meteor.subscribe 'StaticTexts'
    action: ->
        @layout 'layout'
        @render 'openPictures', to: 'content'
        @render 'cover', to: 'cover'
    onBeforeAction: passIfLoggedIn

Router.route '/myPictures',
    waitOn: -> Meteor.subscribe 'StaticTexts'
    action: ->
        @layout 'layout'
        @render 'myPictures', to: 'content'
    onBeforeAction: passIfLoggedIn

handler

Template.adminNav.events
    'click #home': (e) ->
        console.log "home"
        Router.go '/home'
    'click #my-pictures': (e) ->
        console.log "my pictures"
        Router.go '/myPictures'

The problem here is when I navigate to individual route for browser url, it renders just as expected. But when I click on the navigation panel to the other button, for eg: My Pictures, the url in the address bar changes momentarily and reverts back to present route. The page stays unchanged. It does not navigate to other page. Can somebody help me out with this?

EDIT 1 typo in the question.
handler

Template.nav.events
    'click #home': (e) ->
        console.log "home"
        Router.go '/home'
    'click #my-pictures': (e) ->
        console.log "my pictures"
        Router.go '/myPictures'

Solution

  • You are using different template names to make use of the events. So you are binding the click events to the adminNav template, while you want them in the nav template.

    Try this instead

    Template.nav.events
    

    Edit to yours:

    The Router.go has a lower priority than the empty href atrribute of the link, so he jumps into the function of your event, but skips the Router.go and route you to href="" instead.

    <a class="mdl-navigation__link" href="" id="home">Home</a>
    

    should be

    <a class="mdl-navigation__link" id="home">Home</a>
    

    You need to style the link otherwise tho.

    Edit 2:

    Sindis is right, you can use e.preventDefault() in your click event.

    Template.adminNav.events
        'click #home': (e) ->
            e.preventDefault
            console.log "home"
            Router.go '/home'
        'click #my-pictures': (e) ->
            e.preventDefault
            console.log "my pictures"
            Router.go '/myPictures'
    

    This does the trick too.