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.
<ul>
<li><a href="#/" {{action goToLink "index" "#login"}}>Index</a></li>
<li>{{#linkTo about}}About{{/linkTo}}</li>
<li>{{#linkTo contact}}Contact{{/linkTo}}</li>
</ul>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…