Ember.js anchor link

后端 未结 7 1101
时光说笑
时光说笑 2020-12-08 05:22

I have a login box on homepage that I need to link to. The login box has id=\"login\" in html and I have a link to it like this

  • 7条回答
    •  青春惊慌失措
      2020-12-08 06:05

      Query Params

      Updated answer based on the Query Params approach (currently featured flag as of Dec 21 2013)

      Based on alexspellers original JSFiddle, complete demo can be found here: http://jsfiddle.net/E3xPh/

      In your Router, add support for query params

      App.Router.map ->
        @resource 'index', path: '/', queryParams: ['anchor']
      

      Using the Route of your choice, setup a property for the anchor query param in the setupController method.

      App.IndexRoute = Em.Route.extend
        setupController: (controller, context, queryParams) ->
          controller.set 'anchorLocation', queryParams.anchor
      

      Finally in your Controller make an observer for the anchorLocation property.

      App.IndexController = Em.ArrayController.extend
        showAnchor: (->
          $elem = $(@anchorLocation)
          $scrollTo = $('body').scrollTop($elem.offset().top)
        ).observes 'anchorLocation'
      

      Now you can use the following code in your templates to scroll to an anchor or point your browser to /#/?anchor=#login for example.

      {{#linkTo anchor='#login'}}Show login{{/linkTo}}
      

      Simple action approach

      Possible answer based on what you wrote in the comments to the first answer. Hacked together something simple here.

      http://jsbin.com/osEfokE/11

      Clicking the Index link takes you to the IndexRoute and scrolls you to the login box, however the URL is not reflecting this change and typing #login will not work either.

      App.ApplicationRoute = Ember.Route.extend({
          events: {
              goToLink: function(item, anchor) {
                  var $elem = $(anchor);
                  var $scrollTo = $('body').scrollTop($elem.offset().top);
      
                  this.transitionToRoute(item.route).then($scrollTo);  //.transitionTo is depricated
              }
          }
      });
      

      Instead of using linkTo, you will use goToLink in your template when you want to scroll to an anchor.

      • Index
      • {{#linkTo about}}About{{/linkTo}}
      • {{#linkTo contact}}Contact{{/linkTo}}

    提交回复
    热议问题