[英]Ember: send action from one component to another
我刚开始与Ember一起尝试尝试学习它的约定,并且在将操作从一个组件发送到另一个组件时遇到了麻烦。 我将非常感谢对此的一些指导。
我能够显示组件,并且已经弄清楚了如何在组件内嵌套组件。 我创建了一个父组件images-parent
,其中包含2个子组件,分别称为large-image
和thumbnail-list
。 当我单击thumbnail-list
组件中的thumbnail-list
我想获取所单击缩略图的src
并使用它替换large-image
组件中图像的src
。 我在弄清楚如何在Ember中解决此问题时遇到了麻烦。
到目前为止,这是我的代码的一个小提琴: http : //jsfiddle.net/81dLb2xc/
这是我的模板:
<script type="text/x-handlebars">
{{outlet}}
{{images-parent}}
</script>
<script type="text/x-handlebars" id="components/large-image">
<div class="large-img-container">
<img alt="large image" class="js-img" src="http://placeimg.com/200/200" />
</div>
</script>
<script type="text/x-handlebars" id="components/thumbnail-list">
<ul class="thumbnail-container">
<li><img src="http://placekitten.com/110/110" {{action "thumbnailClicked"}} /></li>
<li><img src="http://fillmurray.com/110/110" {{action "thumbnailClicked"}} /></li>
</ul>
</script>
<script type="text/x-handlebars" id="components/images-parent">
{{large-image}}
<p>Click the Image below to swap out the larger image</p>
{{thumbnail-list}}
</script>
和Javascript:
App = Ember.Application.create();
App.ThumbnailListComponent = Ember.Component.extend({
actions: {
thumbnailClicked: function() {
// How do I send this value to the large-image component
// so that the large-image src attibute is replaced?
var source = event.target.src;
console.log(source);
}
}
})
简而言之,您无需交流,但可以交流。 这并不意味着您不能将属性绑定到位于父组件范围内的子组件。 一个例子将最好地说明这一点。
App.ImagesParentComponent = Em.Component.extend({
src: 'http://placeimg.com/200/200',
actions:{
changePic: function(src){
this.set('src', src);
}
}
});
App.ThumbnailListComponent = Ember.Component.extend({
actions: {
thumbnailClicked: function() {
// How do I send this value to the large-image component
// so that the large-image src attibute is replaced?
var source = event.target.src;
this.sendAction('changePic', source);
}
}
});
<script type="text/x-handlebars" id="components/large-image">
<div class="large-img-container">
<img alt="large image" class="js-img" {{bind-attr src=src}} />
</div>
</script>
<script type="text/x-handlebars" id="components/thumbnail-list">
<ul class="thumbnail-container">
<li><img src="http://placekitten.com/110/110" {{action "thumbnailClicked"}} /></li>
<li><img src="http://fillmurray.com/110/110" {{action "thumbnailClicked"}} /></li>
</ul>
</script>
<script type="text/x-handlebars" id="components/images-parent">
{{large-image src=src}}
<p>Click the Image below to swap out the larger image</p>
{{thumbnail-list changePic='changePic'}}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.