繁体   English   中英

可以传入 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 的误解,所以我很感激任何帮助理解该函数的范围,或者,我可以用这种方式代替console.log的函数。

我不认为你可以从.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 甚至更好的https://guides.emberjs.com/release/in-深度主题/动作模式/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM