使用Ember CLI Typescript处理Mixins

Bre*_*rer 3 ember.js typescript

只是想知道如何/什么是使用类型的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?
}
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*cho 7

你有正确的基本方法.经典的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
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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