使用Ember CLI Typescript处理Mixins

时间:2018-03-16 00:29:54

标签: typescript ember.js

只是想知道如何/什么是使用类型化的ember应用程序正确处理mixins的最佳方法。显然,从应用程序中消除mixins是最好的;但是,大多数插件还不支持打字稿。话虽如此,利用ember-simple-auth应用程序路由mixin(或其中任何一个mixin)的最佳方法是什么。我没有测试过以下代码,但我的猜测是这些行应该工作;然而,它只是感觉有点奇怪:

import Route from '@ember/routing/route';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default class ApplicationRoute extends Route.extend(ApplicationRouteMixin, {
  // Prototype Code Here?
}) {
  // Class TS Code Here?
}

再一次,我没有测试过这个,我刚刚开始踏上TS之旅,所以请耐心等待。任何帮助和澄清将不胜感激。

1 个答案:

答案 0 :(得分:5)

你有正确的基本方法。经典的Ember Mixin实例必须绑定到原型。请注意,后面的所有内容同样适用于ES6类; TypeScript类只会受到影响,因为它们大多只是ES6类的类型。

import Route from '@ember/routing/route';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default class ApplicationRoute extends Route.extend(ApplicationRouteMixin, {
  // anything required by the mixin has to go here
}) {
  // normal class code, which can *depend* on the mixin but is effectively
  // invisible to the mixin
}

考虑这一点的一个有用方法是,您传递给类.extend()的对象文字本身只是一个混合。

此模式最适用于向后兼容的解决方案或插件所需的位置。 Mixins很难(最多)使用TypeScript进行正确的类型检查,并且它们与类有惊人和奇怪的交互,如本例所示。 (这里的陌生感同样适用于使用ES6类的普通JavaScript代码。)

每当您编写新代码时,通常最好不要提取功能来执行以下几种选择之一:

  • 使用普通继承,使用单个基类。只要你有一个混合,这通常是最直接的解决方案。

  • 切换到仅定义纯函数,例如在app/lib/validation中,并使用类实例中的适当参数调用它们。