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