Skip to content

Instantly share code, notes, and snippets.

@kmaraz
Created March 19, 2018 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmaraz/56882e45d8e2c46885339d3f7e5984ee to your computer and use it in GitHub Desktop.
Save kmaraz/56882e45d8e2c46885339d3f7e5984ee to your computer and use it in GitHub Desktop.
/**
* ListStore is our custom implementation of general Store,
* which handles manipulation with collections. List store also
* extends the EventEmitter, so it can notify the views about
* its change.
*/
export class EventsStore extends ListStore<Event> {
private config: Config;
constructor(
private ActionTypes: ActionTypes,
private Dispatcher: FluxDispatcher
) {
'ngInject';
super();
// We want to set up initial values for the store
this.reset();
// Here are registered callbacks on the Dispatcher,
// so this store can handle the specific actions and the data.
this.Dispatcher.register((action: Action) => {
switch (action.type) {
case this.ActionTypes.EVENTS_RECEIVE_ALL_EVENTS:
// Most of these methods are implemented in the ListStore
// so this store can be as light weight as possible.
// After each of the actions the `change` event is emitted.
this.init(action.data);
break;
case this.ActionTypes.EVENTS_DELETE_EVENT:
this.eject(action.data.eventUuid);
break;
case this.ActionTypes.EVENTS_DUPLICATE_EVENT:
this.inject(action.data);
break;
case this.ActionTypes.EVENTS_SELECT_EVENT:
// We can emit very specific events, also with the data.
this.emit('selectEvent', action.data);
break;
case this.ActionTypes.EVENTS_SEARCH_SET:
this.setSearch(action.data.search);
break;
case this.ActionTypes.EVENTS_FILTER_SET:
this.setFilter(action.data.filter);
}
});
}
getConfig() {
return cloneDeep(this.config);
}
/**
* This is an example how we can move the sorting and filtering logic
* from the templates and do it before the data is served to the view.
* Therefore in the view we only need to loop through the data and that's it.
*/
getEvents() {
let items = filter(this.getAll(), (i: Event) => i.out_of_date === 0);
// Also we need to be sure that we are returning the copy of the data,
// which in this case is no so explicit as it should be.
items = filter(items, this.getFilterCallback());
return sortBy(items, (i: Event) => -(new Date(i.date_from).getTime()));
}
reset() {
super.reset();
this.config = {};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment