[英]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.