可以传入 console.log 来测试我的应用程序模板中的 Ember.js 组件吗?

Can console.log be passed in to test a Ember.js component from my application template?

我正在构建一个简单的按钮组件,我想通过将 console.log(或其他一些函数)传入我的组件来测试我的点击处理程序是否正常工作。这是在 Ember 4.

app/components/eu-button.hbs 看起来像:

<button
  type={{ this.type }}
  class={{ this.colors }}
  ...attributes
  {{on "click" (fn @onClick) }}
>
  {{#if this.args.icon }}<FaIcon @icon={{ this.args.icon }} />{{/if}}
  {{ this.args.text }}
  {{ yield }}
</button>

实现是:

import Component from '@glimmer/component';

export default class EuButtonComponent extends Component {
  get type() { return "button"; }
  get colors() { return "various classes"; }
}

我从我的 app/templates/application.hbs 中这样调用它:

<EuButton @text="Test" @icon="pencil" @onClick={{ fn console.log "test" }}/>

希望我能看到控制台在单击按钮时打印“测试”一词。但是,我得到:

Uncaught Error: Attempted to resolve a value in a strict mode template, but that value was not in scope: console

我试过在 @onClick={{ fn window.console.log "test" }}@onClick={{ fn document.console.log "test" }} 中传递类似的错误。

我认为我的错误更多是对 Ember(或 Glimmer)的 JS 的误解,所以如果能帮助我理解该函数的范围,或者我可以使用一个函数来代替 [,我将不胜感激。 =16=]这样。

我不认为你可以从 .hbs 文件中做到这一点。但如果那不是你的目标(我怀疑它是)那么你可以添加一个称为动作的函数到你的控制器 application.js (或者你调用组件的任何地方;可能是一个包含组件)文件并且你'可以为所欲为。

import Controller from '@ember/controller';
// add this decorator here
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  // here's your handler
  @action
  onClick(message) {
    console.log(message);
  }
}

然后您就可以从 .hbs:

调用它
<EuButton @text="Test" @icon="pencil" @onClick={{ fn this.onClick "test" }}/>

相关阅读:https://guides.emberjs.com/release/components/component-state-and-actions/#toc_html-modifiers-and-actions or even better https://guides.emberjs.com/release/in-depth-topics/patterns-for-actions/