|
| 1 | +import * as AsyncActions from '../actions/async'; |
| 2 | + |
| 3 | +export default function app() { |
| 4 | + return { |
| 5 | + restrict: 'E', |
| 6 | + controllerAs: 'app', |
| 7 | + controller: AppController, |
| 8 | + template: require('./app.html'), |
| 9 | + scope: {} |
| 10 | + }; |
| 11 | +} |
| 12 | + |
| 13 | +class AppController { |
| 14 | + |
| 15 | + constructor($ngRedux, $scope) { |
| 16 | + const unsubscribe = $ngRedux.connect(this.mapStateToThis, AsyncActions)((selectedState, actions) => { |
| 17 | + this.componentWillReceiveStateAndActions(selectedState, actions); |
| 18 | + Object.assign(this, selectedState, actions); |
| 19 | + }); |
| 20 | + this.options = ['angularjs', 'frontend']; |
| 21 | + this.handleChange = this.handleChange.bind(this); |
| 22 | + this.handleRefreshClick = this.handleRefreshClick.bind(this); |
| 23 | + |
| 24 | + this.fetchPostsIfNeeded(this.selectedReddit); |
| 25 | + } |
| 26 | + |
| 27 | + componentWillReceiveStateAndActions(nextState, nextActions) { |
| 28 | + if (nextState.selectedReddit !== this.selectedReddit) { |
| 29 | + nextActions.fetchPostsIfNeeded(nextState.selectedReddit); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + handleChange(nextReddit) { |
| 34 | + this.selectReddit(nextReddit); |
| 35 | + } |
| 36 | + |
| 37 | + handleRefreshClick() { |
| 38 | + this.invalidateReddit(this.selectedReddit); |
| 39 | + this.fetchPostsIfNeeded(this.selectedReddit); |
| 40 | + } |
| 41 | + |
| 42 | + // Which part of the Redux global state does our component want to receive? |
| 43 | + mapStateToThis(state) { |
| 44 | + const { selectedReddit, postsByReddit } = state; |
| 45 | + const { |
| 46 | + isFetching, |
| 47 | + lastUpdated, |
| 48 | + items: posts |
| 49 | + } = postsByReddit[selectedReddit] || { |
| 50 | + isFetching: true, |
| 51 | + items: [] |
| 52 | + }; |
| 53 | + |
| 54 | + return { |
| 55 | + selectedReddit, |
| 56 | + posts, |
| 57 | + isFetching, |
| 58 | + lastUpdated |
| 59 | + }; |
| 60 | + } |
| 61 | +} |
0 commit comments