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