2016-12-03 58 views
1

當用戶單擊模型時,設置isActive:true並設置所有其他模型isActive:falseEmberjs試圖創建「單選按鈕」類型功能

我有兩個組件和嘗試實現此目的所涉及的路線。

從頂部開始我有一個distro-item這是一個單一模型項目

//components/distro-item 
export default Component.extend({ 
    classNames: 'column is-2', 
    tagName: 'div', 
    isActive: false, 

    actions: { 
    toggleActive (distro) { 
     this.sendAction('toggleActive', distro); 
    } 
    } 

}); 

然後我有它包含所有的distro-item小號

// components/distro-holder 
export default Ember.Component.extend({ 
    sortedDistros: Ember.computed.sort('distros', 'sortDefinition'), 
    sortDefinition: ['sortOrder:acs'], 

    distros: computed('[email protected]', function() { 
    console.log("triggered"); 
    }), 

    actions: { 
    toggleActive(distro) { 
     this.sendAction('toggleActive', distro); 
    } 
    } 

}); 

最後的路線保持器組件

//route/new 
export default Route.extend(AuthenticatedRouteMixin, { 

    selectedDistro: undefined, 

    model() { 
    return RSVP.hash({ 
     distros: get(this, 'store').findAll('distro'), 
    }); 
    }, 

    setupController(controller, models) { 
    controller.setProperties(models); 
    }, 

    actions: { 
    toggleActive(distro) { 
     this.set('selectedDistro', distro); 
    }, 
    } 

}); 

我不確定這三件事中的哪一件應該是負責過程的每個部分。最初的想法是,發行人應該負責確定每個發行版應該處於哪個狀態,並將其發送迴路線。然而,無論我嘗試什麼,我都無法獲得計算屬性來觸發。這應該在路線上還是其他地方?

documentation example似乎具有相當於發行人的權利。當我改變isActive的狀態它不會像我所期望的那樣發生...

任何幫助表示讚賞!

+0

您可以將此'selectedDistro'屬性和toggleActive操作移動到控制器並將'distros'數組傳遞到組件。 – maheshiv

回答

1

取代發行人的計算屬性,設置selectedDistro屬性,並將其傳遞給每個發行版項目。然後,每個發行項可以知道,如果它的數據是一樣的數據selectedDistro,或者false一個selected狀態設置爲true如果不是(類似於單個無線電如何知道其無線電組值)。

actions: { 
    toggleActive(distro) { 
    this.sendAction('toggleActive', distro); // goes up to distro-holder 
    }, 
}, 

的發行版保持器組件接收該數據,並集:

在發行項分量,當點擊一個發行項時,它通過toggleActive動作將其數據發送到發行版保持器所述selectedDistro屬性:

selectedDistro: null, 

actions: { 
    toggleActive(distro) { 
    this.set('selectedDistro', distro); 
    this.sendAction('setName', distro); // goes up to the controller 
    } 
} 

的發行項目組件都有selected計算屬性聽selectedDistro,並設置selected,對於本身爲真或假(這意味着,只有一個d ISTRO項目將在任何給定時間被選擇):

selected: Ember.computed('selectedDistro', function() { 
    return this.get('selectedDistro.name') === this.get('distro.name'); 
}), 

爲了證明獲取數據進一步向上進入控制器,發行持有者發送setName動作,其中,所述控制器接收並執行:

selectedDistro: null, 

actions: { 
    setName(distro) { 
    this.set('selectedDistro', distro.name); 
    } 
} 

如果不知道,此方法使用Ember約定Data Down, Actions Up。確保您將數據(以及要使用的操作)傳遞到每個組件中,然後將操作(通過數據)發送回去可能會很難理解,並且一開始就會變得很困難。

我創建了一個Ember Twiddle example來演示。