如何使用Ember.js的新路由器以编程方式在路由之间转换

46scxncf  于 2022-11-05  发布在  其他
关注(0)|答案(3)|浏览(129)

问题:

如何使用新的Ember.js Router以编程方式转换到新的路由?

背景/上下文

对于旧的Ember.js Router,您可以使用路由器的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)**调用App.router示例上的send方法

> 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'
xoefb8l8

xoefb8l81#

假设路由器定义如下:

App.Router.map ->
  this.resource('old_route', {path : ""})
  this.resource('new_route', {path : ":model_id"})

当您将控制器作为上下文时,可以使用old_route.transitionToRoute()函数移动到new_route

从控制器

this.get('target').transitionToRoute('new_route', model_instance)

this.get('target')-从controller返回当前路由
从视图

this.get('controller').get('target').transitionToRoute('activity_detail', activity)

注意事项
函数 *transitionTo()在1.0.0.RC3中已被修改为deprecated

6yjfywim

6yjfywim2#

您可以将transitionTo与新的路由器API一起使用,但是您必须以不同的方式访问路由器示例。
有关可能性,请参阅问题Access instance of new Ember Router的答案。

0wi1tuuw

0wi1tuuw3#

您使用{{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");
        });
    });

希望这对你有帮助:)

相关问题