Chris Hough
Chris Hough

Reputation: 3558

emberjs go to anchor from another view

Currently I am using the ember cli project to build my ember application, but I am running into an issue trying to configure my navigation. The following code block works on the index router, however, I am running into an issue on my other routers. The goToAnchor section allows me to navigate to in page anchor tags on a single infinite scroll like home page, but when I go to other views i.e. my /terms page I need the menu to be able to click back to the home page, ideally without refreshing the browser.

Is this possible without the refresh?

Index Router:

export default Ember.Route.extend({
    actions: {
        goToAnchor: function(item,anchor) {
            var $elem, $scrollTo;
            $elem = $('#' + anchor);
            $scrollTo = $('body').animate({
                scrollTop: $elem.offset().top-15
            }, parseInt(ENV.CONFIG.PRODUCT.SCROLL_SPEED));
            this.transitionTo(item.route).then($scrollTo);
        }
    }
});

Navigation:

<section class="top-bar-section center">
    <ul class="nav-header">
        <li><a {{action goToAnchor 'index' 'menu1'}}>menu1</a></li>
        <li><a {{action goToAnchor 'index' 'menu2'}}>menu2</a></li>
        <li><a {{action goToAnchor 'index' 'menu3'}}>menu3</a></li>
        <li><a {{action goToAnchor 'index' 'menu4'}}>menu4</a></li>
    </ul>
</section>

Current setup at the time of this post:

DEBUG: ------------------------------- 
DEBUG: Ember      : 1.5.1 
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba 
DEBUG: Handlebars : 1.3.0 
DEBUG: jQuery     : 2.1.1 
DEBUG: ------------------------------- 

Upvotes: 0

Views: 784

Answers (1)

selvagsz
selvagsz

Reputation: 3872

Hi Chris I had just looked into your code and was able to identify the gotchas

  1. Your terms page's route is legal/tou. When you click the navigation menu from the terms page, you action is bubbled via legal/tou => application routes (child => parent hierarchy). Hence the Nothing handled in the action goToAnchor was thrown. So first step is to move up your goToAnchor logic from index route to application route.

  2. Secondly, in the goToAnchor action you are trying to query the DOM before the template gets rendered. Hence, it blows up. You need to query the DOM after the template is rendered. You should make use of afterRender queue of Ember RunLoop. To know more about Ember Runloops refer the docs here

    //routes/application.js
    
    export default Ember.Route.extend({
    actions: {
     goToAnchor: function(route,anchor) {
        var $elem, $scrollTo;
        this.transitionTo(route).then(function() {
          Em.run.schedule('afterRender', function(){
            $elem = $('#' + anchor);
            $('html,body').animate({
                scrollTop: $elem.offset().top-15
            }, 500);              
          });
        });
      }
     }
    });
    

Upvotes: 1

Related Questions