更改视图时,Emberjs会滚动到顶部

xMa*_*tin 21 ember.js

切换应用程序的主视图(重新连接应用程序控制器主出口的新路径)时,我希望页面滚动到顶部.否则,我导航到另一个类似页面的视图并且视口仍然在我离开的地方丢失时有点奇怪.

我破解了一个解决方案并想知道是否有更好的方法,或者是否有人有同样的事情.

这是我做的:

App.ApplicationController = Ember.Controller.extend({
  connectOutlet: function(){
    window.scrollTo(0, 0);
    this._super.apply(this, arguments);
  }
});
Run Code Online (Sandbox Code Playgroud)

Mic*_*nin 19

@ Baruch的解决方案很好,但是当我实现它时,我在应用程序状态中对元素进行渲染,并且在不需要时会导致scrollTop.

我发现这更有效,因为它只在路径更改上运行:

App.ApplicationController = Ember.Controller.extend({

  currentPathChanged: function () {
    window.scrollTo(0, 0);
  }.observes('currentPath')

});
Run Code Online (Sandbox Code Playgroud)


Bar*_*uch 9

我用以下代码实现了这个目的:

Ember.Route.reopen({
  render: function(controller, model) {
    this._super();
    window.scrollTo(0, 0);
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 7

咖啡脚本:

Ember.Route.reopen
    activate: ->
      @_super()
      window.scrollTo(0, 0)
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

Ember.Route.reopen({
  activate: function() {
      this._super();
      window.scrollTo(0, 0);
  }
});
Run Code Online (Sandbox Code Playgroud)


Mil*_*Joe 6

你可能应该尝试扩展Ember.Route并添加你window.scrollToenter回调.然后,不是使用Ember的Route叶子路线,而是打电话给你的路线.extend(),因此当您进入路线/州时,它们会自动向上滚动.此类似的东西:

// define your custom route and extend "enter"
var MyRoute = Em.Route.extend({
    enter: function(router) {
        // for now on, all the routes that extend this, 
        // will fire the code in this block every time
        // the application enters this state
        // do whatever you need to do here: scroll and whatnot
    }
});

App.Router = Em.Router.extend({
    enableLogging: true,
    location: 'hash',
    index: Em.Route.extend({
            route: '/',
            connectOutlets: function(router) {
                ...
            },
            // on your leaf routes, use your own custom route that 
            // does your scroll thing or whatever you need to do 
            home: MyRoute.extend({
                route: '/',
                connectOutlets: function (router, context) {
                     ...
                }
            }),
            // other routes...
       })
});
Run Code Online (Sandbox Code Playgroud)

是否有意义?