In Flux, Store manages the application state for a particular domain within your application. This basically means that stores manage the data, data retrieval methods, and dispatcher callbacks.
Lets take a look at a basic Store:
import { EventEmitter } from "events";
import dispatcher from "../dispatcher";
class TodoStore extends EventEmitter { //Store class
constructor() {
super()
this.todos = [ //object whcih stores Store data
{
id: 113464613,
text: "React JS"
},
{
id: 235684679,
text: "Angular JS"
},
];
}
createTodo(text) {
const id = Date.now();
this.todos.push({
id,
text
});
this.emit("change");
}
getAll() {
return this.todos;
}
handleActions(action) { //registered callback method
switch(action.type) {
case "CREATE_TODO": {
this.createTodo(action.text);
break;
}
case "RECEIVE_TODOS": {
this.todos = action.todos;
this.emit("change"); //change event firing
break;
}
}
}
}
const todoStore = new TodoStore;
dispatcher.register(todoStore.handleActions.bind(todoStore)); //registering the store method to dispatcher.
export default todoStore;
Here,
import { EventEmitter } from "events";
EventEmitter is used to extend store class so that any method from store class can fire any event.
How to Register store method to dispatcher?
dispatcher.register(todoStore.handleActions.bind(todoStore));