2016-08-19 29 views
1

我知道這是違反數據下來的行動理念,但是,跟着它,我的父組件看起來是非常人口稠密。什麼是從「父」到「孩」組件溝通的燼way方式?

所以,我正在尋找是否有另一種方式。

示例案例: 我有一個父組件擁有「filters」,「table」和「options」。現在,當用戶從選項中選擇另一個表格時,必須重置過濾器。 因此,我需要觸發父組件的重置過濾器。

回答

1

您可以將父組件屬性綁定到子組件,並且您可以通過組件掛鉤對沒有觀察者的父組件屬性更改作出反應。 這將堅持數據關閉操作(DDAU)原則並避免觀察者。

Ember-twiddle

在下面的例子中, 每當selectedOptionId在母體組分改變,則在子組件(我的表)將開始通過按照該次序(didUpdateAttrsdidReceiveAttrswillUpdatewillRender調用以下鉤子重新描繪,didUpdate,didRender)。您將從didUpdateAttrs和didReceiveAttrs鉤子的options參數獲得newAttrsoldAttrs屬性。

第一次渲染didReceiveAttrs鉤子中不會有options.oldAttrs

模板/ application.hbs

{{parent-component }} 
{{outlet}} 

模板/組件/父 - component.hbs

{{my-table selectedOptionId=selectedOptionId}} 
<button {{action 'changeOption'}}> Change Option </button> 
{{yield}} 

**組件/父 - component.js

import Ember from 'ember'; 

export default Ember.Component.extend({ 
    selectedOptionId:1, 
    actions:{ 
    changeOption(){ 
     this.set('selectedOptionId',2); 
    } 
    } 
}); 

模板/組件/我-table.hbs

{{selectedOptionId}} 
{{yield}} 

組件/我-table.js

import Ember from 'ember'; 

export default Ember.Component.extend({ 
    didReceiveAttrs(options){ 
    this._super(...arguments);  
    //this will run both initial render and rerender. 
    //For initial rendering alone options.oldAttrs will not be available 
    }, 
    didUpdateAttrs(options){ 
    this._super(...arguments); 
    //this will run only for the rerender 
    if(options.oldAttrs.selectedOptionId.value !== options.newAttrs.selectedOptionId.value) { 
     this.send('triggerOptionChangeEvent'); 
    } 
    }, 
    actions:{  
    triggerOptionChangeEvent(){ 
     console.log('triggerOptionChangeEvent ',this.get('selectedOptionId')); 
    } 
    } 
}); 

更新:ember guides

注意:觀察者經常被新的Ember開發者過度使用。觀察者在Ember框架中大量使用,但對於Ember應用程序開發人員面臨的大多數問題,計算屬性是適當的解決方案。

所以總是遠離使用觀察員。我們甚至不應該在生命週期鉤子方法中使用options。那是deprecated。所以我們應該手動查找特定的屬性是否改變。這是正確的方法。請參閱this RFC for more details。它包含正確的方法來避免使用opions財產didReceiveAttrs

請參閱stefan penner excellant talk以解決問題而不使用觀察者。

+0

做什麼「觀察員」做,但沒有使用它。尼斯:) –

+0

爲什麼使用這種方法而不是觀察者更好? – Dmitro

+0

@Dmitro我更新了我的答案 – kumkanillam

相關問題