如何使用新的Ember.js路由器以编程方式转换到新路由?
使用旧的Ember.js路由器,您可以使用路由器的send
方法以编程方式在路由/状态之间转换:
//OLD Router Syntax
App = Ember.Application.create({
Router: Ember.Router.extend({
root: Ember.Route.extend({
aRoute: Ember.Route.extend({
route: '/',
moveElsewhere: Ember.Route.transitionTo('bRoute')
}),
bRoute: Ember.Route.extend({
route: '/someOtherLocation'
})
})
})
});
App.initialize();
程序转换:
App.get('router').send('moveElsewhere');
鉴于新的Ember.js路由器(如下)我们如何完成同样的事情?
//NEW Router Syntax
App.Router.map(function(match) {
match('/').to('aRoute');
match('/someOtherLocation').to('bRoute');
});
这可能不对,对吧?:
window.location = window.location.href + "#/someOtherLocation";
1)在send
实例上调用App.router
方法
> App.router.send("moveElseWhere")
TypeError: Cannot call method 'send' of undefined
2)明确声明路线并设置事件
App.ARoute = Ember.Route.extend({
events: {
moveElseWhere: function(context){
this.transitionTo('bRoute');
}
}
);
App.UploadRoute.moveElseWhere()
TypeError: Object (subclass of Ember.Route) has no method 'moveElseWhere'
注意:在撰写本文时,Ember.js Router documentation仍然引用旧路由器,其中Ember.js Router guide引用新路由器
答案 0 :(得分:9)
假设此路由器定义:
App.Router.map ->
this.resource('old_route', {path : ""})
this.resource('new_route', {path : ":model_id"})
当您将控制器作为上下文时,可以使用new_route
函数移动到old_route.transitionToRoute()
。
this.get('target').transitionToRoute('new_route', model_instance)
this.get('target')
- 从控制器返回当前路线
this.get('controller').get('target').transitionToRoute('activity_detail', activity)
函数* transitionTo()在1.0.0.RC3中已deprecated
答案 1 :(得分:4)
我现在还不知道像Ember.Route.transitionTo()
这样的短片。
要获得相同的行为,您可以在路由中定义events
对象,然后调用route.transitionTo()
。
根据你的例子,这应该是这样的:
UPDATE 由于此提交:https://github.com/emberjs/ember.js/commit/6dab9beccf4a2ae700633dfd4811018e0bea5028事件的上下文是路由本身。
App.Router.map(function(match) {
match('/').to('aRoute');
match('/someOtherLocation').to('bRoute');
);
App.ARoute = Ember.Route.extend({
events: {
moveElseWhere: function(context){
this.transitionTo('bRoute');
}
}
});
答案 2 :(得分:3)
您可以将transitionTo
与新路由器API一起使用,但必须以不同方式访问路由器实例。
请参阅问题Access instance of new Ember Router的答案。
答案 3 :(得分:1)
使用{{linkTo}}帮助程序触发指向新路线的链接:
#your template
{{#linkTo allTodos activeClass="selected"}}All{{/linkTo}}
#your router
App.Router.map(function (match) {
match("/").to("todos", function (match) {
match("/").to("allTodos"); // will fire this router
match("/active").to("activeTodos");
match("/completed").to("completedTodos");
});
});
希望这会有所帮助:)