[英]Setting value for specific ember component
我已經制作了一個組件,可以從代碼框中復制一些代碼。 組件javascript如下所示:
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'code',
classNames: ['lm-code-box'],
dataTarget: null,
dataTrigger: Ember.computed('dataTarget',
function() {
return `.${this.get('dataTarget')}`;
}
),
copyAction: null,
icon: 'ion-code',
copyStatus: null,
buttonText: 'Copy',
didInsertElement() {
this.clipboard = new Clipboard('.lm-button--copy');
this.clipboard.on('success',(e) => {
this.set('icon','ion-checkmark');
this.set('copyStatus','success');
this.set('buttonText','Copied');
e.clearSelection();
});
this.clipboard.on('error',(e) => {
this.set('icon','ion-android-warning');
this.set('copyStatus','error');
this.set('buttonText','Error');
});
},
willDestroyElement() {
this.clipboard.destroy();
}
});
組件代碼如下所示:
<a class="lm-button--copy {{buttonClass}}" data-clipboard-target={{dataTrigger}} data-clipboard-action={{copyAction}}>
{{buttonText}}
<i class="icon {{icon}}"></i>
</a>
<pre class="{{dataTarget}}">
{{yield}}
</pre>
然后在我的模板中,代碼如下所示:
{{#lm-code-copy dataTarget="testOne"
copyAction="copy"}}
test one
{{/lm-code-copy}}
{{#lm-code-copy dataTarget="testTwo"
copyAction="copy"}}
test two
{{/lm-code-copy}}
一切都很好,但是在塊中:
this.set('icon','ion-checkmark');
this.set('copyStatus','success');
this.set('buttonText','Copied');
更改呈現的兩個組件上的那些鍵值。 如何告訴ember僅更改當前組件的值? 我以為this
會設置上下文,但似乎並不能解決問題。
我會在這里碰碰運氣,因為您沒有提供組件模板。 我認為您的問題可能出在您的CSS選擇器上
this.clipboard = new Clipboard('.lm-button--copy');
您始終使用該選擇器來定位頁面中的所有.lm-button--copy
元素。 這意味着每個組件實例將有一個單獨的this.clipboard
引用,但都指向同一個dom元素。
另外, this
你指的是不是組件:
this.clipboard.on('success',(e) => { <--- This `this` is your component
this.set('icon','ion-checkmark');
this.set('copyStatus','success'); <---- These `this` are the context of the invoking success handler (you can set a break point here to see its not the ember component)
this.set('buttonText','Copied');
e.clearSelection();
});
您可能想要這樣的東西(假設Clipboard
內容也可以接收一個dom元素):
this.clipboard = new Clipboard(this.$('.lm-button--copy'));
在Ember組件中, this.$
表示包裝該組件的外部div。 這樣,您將僅選擇組件內的元素。 我認為您可能需要什么。
@Pedro Rio很近。 使用剪貼板 .js,您必須使用syntanx傳遞類似於jquery的DOM元素,例如clipboard = new Clipboard('.class-name')
或clipboard = new Clipboard('#id-name')
。 不知怎的,在灰燼世界的范圍內this
是必然的Clipboard.js的查詢范圍。 因此,解決方法是使用Ember的jQuery語法將剪貼板范圍內的每個按鈕項。
this.clipboard = new Clipboard(this.$(`.lm-button--copy`).get(0));
請注意,沒有.
在this.$
之后,如其他答案中所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.