Adding the store

The store will act as the data source for our state but will also be able tell any listeners when a change to the store happens:

// demo/store.js

import dispatcher from './dispatcher';

function selectIndex(index) {
store["selectedIndex"] = index;
}

// 1) store registers with dispatcher
dispatcher.register(message => {
switch (message.type) {
// 3) message is sent by dispatcher ( that originated from the first view)
case "SELECT_INDEX":
selectIndex(message.data);
// 4) listener, a view, is being notified of the change
store.emitChange();
break;
}
});

class Store {
constructor() {
this.listeners = [];
}

// 2) listener is added by a view
addListener(listener) {
if (!this.listeners["change"]) {
this.listeners["change"] = [];
}

this.listeners["change"].push(listener);
}

emitChange() {
if (this.listeners["change"]) {
this.listeners["change"].forEach(cb => cb());
}
}

getSelectedItem() {
return store["selectedIndex"];
}
}

const store = new Store();
export default store;