Маршрутизатор Meteor Iron — возможен обратный вызов Router.go?

У меня есть ссылка, которую я хочу, чтобы пользователь нажал. Когда они нажимают ее, маршрутизатор переходит к определенному шаблону, а затем запускает код Smoothscroll.js для анимации и прокрутки вниз до тега привязки.

      //When the user clicks on the link to get to the #contact anchor...
      //The code below does not work.
      Router.go('index');
      $('html,body').animate({
          scrollTop: $('#contact').offset().top
      }, 1200);

Router.go('index') работает нормально.

      $('html,body').animate({
          scrollTop: $('#contact').offset().top
      }, 1200);

Работает также сам по себе на индексном шаблоне.

Но когда я пытаюсь запустить их вместе, роутер уходит в индекс, но прокрутка не работает.

Любая идея, как я могу это сделать?

ИЗМЕНИТЬ

Это то, что у меня есть для последнего Meteor 1.0+ и пути типа /#contact

Router.route('/', {
  name: 'index'
});

Router.onAfterAction(function() {
    var self = this;
    // always start by resetting scroll to top of the page
    $(window).scrollTop(0);
    // if there is a hash in the URL, handle it
    if (this.params.hash) {
        // now this is important : Deps.afterFlush ensures that iron-router rendering
        // process has finished inserting the current route template into DOM so we
        // can manipulate it via jQuery, if you skip this part the HTML element you
        // want to scroll to might not yet be present in the DOM (this is probably
        // why your code fails in the first place)
        Tracker.afterFlush(function() {

            if (typeof $("#" + self.params.hash).offset() != "undefined"){
                var scrollTop = $("#" + self.params.hash).offset().top;

                $("html,body").animate({
                    scrollTop: scrollTop
                });

            }

        });
    }
});

person fuzzybabybunny    schedule 14.08.2014    source источник


Ответы (1)


Если вы не делаете что-то необычное, вы, вероятно, не захотите использовать Router.go и вместо этого позволите iron-router управлять маршрутизацией при щелчке привязки, как это обычно делается.

Что касается прокрутки к элементу, то я использую хук onAfterAction, он поддерживает любой маршрут и любой хэш (/anyroute#anyhash).

Router.onAfterAction(function() {
  // always start by resetting scroll to top of the page
  $(window).scrollTop(0);
  var hash=this.params.hash;
  // if there is a hash in the URL, handle it
  if (hash) {
    // now this is important : Tracker.afterFlush ensures that iron-router
    // rendering process has finished inserting the current route template
    // into DOM so we can manipulate it via jQuery, if you skip this part
    // the HTML element you want to scroll to might not yet be present in
    // the DOM (this is probably why your code fails in the first place)
    Tracker.afterFlush(function() {
      var element=$("#"+hash);
      var scrollTop = element.offset().top;
      $("html,body").animate({
        scrollTop: scrollTop
      });
    });
  }
});
person saimeunt    schedule 14.08.2014
comment
Круто, попробую. Где найти Deps.autoFlush? Я не могу найти упоминания об этом в документации. Этого определенно нет в Руководстве по Метеору. - person fuzzybabybunny; 14.08.2014
comment
Привет, просто интересно, как это будет выглядеть для последнего метеора 1.0.2.1? Также я получаю неопределенность при вызове $(#.. - person aginsburg; 12.01.2015
comment
К вашему сведению, я создал версию Meteor 1.0 здесь и опубликовал ее как проблему с железным маршрутизатором: github.com/EventedMind/ железный маршрутизатор/проблемы/1171 - person aginsburg; 13.01.2015
comment
@aginsburg, я обновил свой OP, чтобы выделить код для последнего Meteor. - person fuzzybabybunny; 19.06.2015
comment
Спасибо @fuzzybabybunny - person aginsburg; 20.06.2015