[英]Reset Ember Component on Button Click
背景:
我在模板中有一個組件。 該組件是一個彈出框,單擊按鈕即可打開。 此彈出框內部具有復選框(默認情況下全部設置為false)。 當我關閉此彈出框時,我想將所有變量完全重置為默認設置,即所有復選框現在都已關閉。 當前,當我重新打開此彈出框時,以前的復選框仍處於選中狀態。 如何執行此操作而無需手動切換每個復選框:
this.set("checkbox1", false);
this.set("checkbox2", false);
so on...
有沒有可以自動重置組件並取消選中所有復選框並將變量設置回false的功能?
相關代碼:
模板:app / template / home.hbs
{{popup-modal isOpen=showModal}}
組件:app / template / components / popup-modal.hbs
{{#bs-modal body=false footer=false open=isOpen title="popup box" closeAction=(action "cancel") submitAction=(action "submit")}}
{{#bs-modal-body}}
<label><input type="checkbox" {{action "toggleCheckbox" "checkbox1" on="click" preventDefault=false}}/> Checkbox 1</label>
<label><input type="checkbox" {{action "toggleCheckbox" "checkbox2" on="click" preventDefault=false}}/> Checkbox 2</label>
{{/bs-modal-body}}
{{bs-modal-footer closeTitle="Cancel" submitTitle="Ok"}}
{{/bs-modal}}
組件JS:app / components / popup-modal.js
import Ember from 'ember';
export default Ember.Component.extend({
checkbox1: false,
checkbox2: false,
actions: {
submit(){
// close box
this.set('isOpen', false);
},
cancel(){
// how do I reset component here?
// in other words, make all checkbox set to false
// without manually doing it like below:
this.set("checkbox1", false);
this.set("checkbox2", false);
},
toggleCheckbox(checkbox){
this.toggleProperty(checkbox);
}
}
});
很多時候我也有類似的情況。 有時這些值不僅是布爾值,還包括字符串或數字(非零)值,因此我還需要能夠將組件的某些屬性重置為初始狀態。
我認為重置組件的所有屬性並不是很好(我什至不知道是否有可能),因為有人想添加一些屬性,即使用戶單擊“取消”按鈕也應保持其狀態。
我認為好主意是做一些將所有屬性設置為初始狀態的函數。 例如,您的代碼如下所示:
import Ember from 'ember';
export default Ember.Component.extend({
// EmberJS Component hook fired after component have been initialized
init() {
this._super(...arguments);
this.setInitialState();
},
setInitialState(){
this.set("checkbox1", false);
this.set("checkbox2", false);
},
actions: {
submit(){
// close box
this.set('isOpen', false);
this.setInitialState();
},
cancel(){
this.setInitialState();
},
toggleCheckbox(checkbox){
this.toggleProperty(checkbox);
}
}
});
PS。 如果組件沒有被銷毀,那么無需重新初始化組件即可生存並更改其狀態(例如屬性),這是很好的。 因為當某些屬性發生更改時,不會重新呈現整個組件,而是僅更改了已更改的內容(在這種情況下,僅復選框)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.