Emberjs-comp-lifecycle-willdestroy
提供:Dev Guides
willDestroyElementを使用したデタッチとティアダウン
_willDestroyElement_フックをトリガーすることにより、DOMからコンポーネント要素を削除できます。
構文
import Ember from 'ember';
export default Ember.Component.extend ({
...
willDestroyElement() {
//code here
},
...
})
例
以下の例では、DOMからコンポーネント要素を削除する_willDestroyElement_フックの使用について説明します。 次のコードを追加するには、名前のインデックスでコントローラーを作成し、_app/controller/_からファイルを開きます-
import Ember from 'ember';
export default Ember.Controller.extend ({
showComponent: true,
laterCount: 0,
buttonText: Ember.computed('showComponent', function() {
let showing = Ember.get(this, 'showComponent');
if (showing) {
return 'Remove';
} else {
return 'Add';
}
}),
actions: {
toggleComponent() {
this.toggleProperty('showComponent');
},
updateLaterCount() {
Ember.set(this, 'laterCount', Ember.get(this, 'laterCount') + 1);
}
}
});
_post-action_という名前のコンポーネントを作成します。これは、_app/components/_の下で定義されます。
_post-action.js_ファイルを開き、次のコードを追加します-
import Ember from 'ember';
export default Ember.Component.extend ({
runLater: null,
didInsertElement() {
let timeout = Ember.run.later(this, function() {
Ember.Logger.log('fired this after 1 seconds...');
this.sendAction();
}, 500);
Ember.set(this, 'runLater', timeout);
},
willDestroyElement() {
Ember.run.cancel(Ember.get(this, 'runLater'));
}
});
今、次のコードでコンポーネントテンプレートファイル_post-action.hbs_を開きます-
<h2>finddevguides</h2>
_index.hbs_ファイルを開き、次のコードを追加します-
<h5>Count for clicks: {{laterCount}}</h5>
<button {{action 'toggleComponent'}}>{{buttonText}}</button>
{{#if showComponent}}
{{post-action action="updateLaterCount"}}
{{/if}}
{{outlet}}
出力
emberサーバーを実行します。次の出力が表示されます-
Ember.jsコンポーネントwillDestroyElement Attr
最初のクリック数は1です。 あなたが_Removeボタン_をクリックすると、それはテキストを削除します-
Ember.jsコンポーネントwillDestroyElement Attr
次に、_Add_ボタンをクリックすると、クリック数が増加し、テキストが表示されます-