在没有 sendAction 的组件中干净地 Ember transitionToRoute [英] Ember transitionToRoute cleanly in a component without sendAction

查看:23
本文介绍了在没有 sendAction 的组件中干净地 Ember transitionToRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Ember 组件中干净地调用 transitionToRoute?

How can transitionToRoute be called cleanly from within an Ember component?

它可以将控制器注入组件并调用控制器的 transitionToRoute 函数,但是如果可能的话,我想要更优雅的东西.

It works with injecting a controller into the component and calling the controller's transitionToRoute function, however I'd like something a little more elegant if possible.

它目前在组件的 javascript 中的样子:

What it currently looks like inside the component's javascript:

// this.controller is injected in an initializer
this.controller.transitionToRoute("some.target.route.name");

组件的 javascript 中什么会更好:

What would be nicer in the component's javascript:

transitionToRoute("some.target.route.name");

一个目标是在不使用 sendAction 的情况下执行此操作,因为此特定组件具有单一目的并且应始终转换到相同的路由.没有必要让任何其他 Ember 工件知道这个组件总是转换到的路径,也不需要关联的间接.目标路由的责任由这个组件所有.

One goal is do this without using sendAction as this particular component has a single purpose and should always transition to the same route. There's no need for any other Ember artifacts to be aware of the route this component always transitions to, there's no need for the associated indirection. The responsibility for the target route is owned by this component.

推荐答案


<小时>

更新请查看其他最近的答案,了解如何在较新的 Ember 版本中以更少的代码实现这一目标,如果它们适合您,请投票 - 谢谢!



UPDATE Please see the other more recent answers for how to achieve this with less code in newer Ember versions, and vote those up if they work for you - Thanks!

router注入到组件中并调用this.get('router').transitionTo('some.target.route.name').

Inject the router into the components and call this.get('router').transitionTo('some.target.route.name').

要将 router 注入所有组件,请在 app/initializers/component-router-injector.js 编写一个初始化程序,内容如下:

To inject the router into all components, write an initializer at app/initializers/component-router-injector.js with the following contents:

// app/initializers/component-router-injector.js
export function initialize(application) {
  // Injects all Ember components with a router object:
  application.inject('component', 'router', 'router:main');
}

export default {
  name: 'component-router-injector',
  initialize: initialize
};

组件中的示例用法:

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    submit: function() {
      this.get('router').transitionTo('some.target.route.name');
    }
  }
});

这篇关于在没有 sendAction 的组件中干净地 Ember transitionToRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆