The view

To tell the view that something has happened and act on it, three things need to happen:

  • The view needs to register with the store as a listener
  • The store needs to send off an event conveying that a change has happened
  • The view needs to reload its data

Starting with the store, we need to build it out so that you can register as a listener to its events. We therefore add the addListener() method:

// store-with-pubsub.js

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

// registering with the dispatcher
dispatcher.register(message => {
switch (message.type) {
case "SELECT_INDEX":
selectIndex(message.data);

// signals to the listener that a change has happened
store.emitChange();
break;
}
});

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

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;

In the preceding code, we also add the ability to emit an event with the addition of the emitChange() method. You can easily switch out this implementation to use an EventEmitter or similar. So now is the time to hook up our view to the store. We do so by calling the addListener() method like so:

// view.js

import store from "./store-with-pubsub";

class View {
constructor(store) {
this.index = 0;
store.addListener(this.notifyChanged);
}

// invoked from the store
notifyChanged() {
// rereads data from the store
this.index = store.getSelectedItem();

// reloading the data
render();
}

render() {
const elem = document.getElementById('view');
elem.innerHTML = `Your selected index is: ${this.index}`;
}
}

let view = new View();

// view.html
<html>
<body>
<div id="view"></div>
</body>
</html>

In the preceding code, we implement the notifyChanged() method, which when called invokes the getSelectedItem() method from the store and thereby receives the new value.

At this point, we have described the whole chain: how one view receives a user interaction, turns that into an action, which is then dispatched to a store, which updates the store's state. The store then emits an event that the other view is listening to. When the event is received, in the view the state from the store is reread and the view is then free to render this state, which it just read in, the way it sees fit.

We have described two things here:

  • How to set up the flow
  • How the information flows in Flux

Setting up the flow can be depicted with the following diagram:

As for the second scenario, how the information flows through the system, it can be depicted in the following way:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.161.228