【问题标题】:How to programmatically transition between routes using Ember.js' new Router如何使用 Ember.js 的新路由器以编程方式在路由之间转换
【发布时间】:2012-12-20 14:24:37
【问题描述】:

问题:

您如何使用新的 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)App.router实例上调用send方法

> App.router.send("moveElseWhere")
TypeError: Cannot call method 'send' of undefined

2)显式声明Route并设置事件

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 指的是新路由器

【问题讨论】:

标签: ember.js ember-router


【解决方案1】:

假设这个路由器定义:

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') - 从控制器返回当前路由

从一个视图

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

注意

函数 *transitionTo() 在 1.0.0.RC3 中已经是 deprecated

【讨论】:

  • 看起来您不再需要执行get("target") transitionToRoute 函数可以直接从控制器本身访问。
【解决方案2】:

您可以将transitionTo 与新的路由器 API 一起使用,但您必须以不同的方式访问路由器实例。

请参阅问题Access instance of new Ember Router 的答案以了解可能性。

【讨论】:

    【解决方案3】:

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

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2017-09-03
      • 2013-01-09
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2017-08-25
      相关资源
      最近更新 更多