So I'm writing a small note taking application. Here are the various entities and the events via which they've to update their state / view.
| Notebook | Notes | Status bar |
|-----------------------|------------------|-----------------------|
| Note added | Notebook changed | Notebook changed |
| Note deleted | Notebook deleted | Notebook deleted |
| Note completed | Notebook added | Date changed |
| Hours added / changed | Date changed | Note added |
| Date changed | | Note deleted |
| | | Note completed |
| | | Hours added / changed |
| | | Date changed |
I'm planning to use a variation of the observer pattern to handle the events between the various entities.
+---------------+
+--------------+ | |
| | | Notebook |
| Notes | | |
| | +-------+-------+
+--------------+ |
| +--------------+ |
| | | |
+--------------> Mediator <---------------+
| |
+-------^------+
|
|
+----------------+ |
| | |
| Status bar +---------------+
| |
+----------------+
The mediator will receive all the events and then pass them onto the appropriate subscribers for that event.
Lets take an example - User updates a note and marks it completed, in which case the following has to be done,
- Number of completed notes in the notebook should change.
- Number of completed notes in the status bar should change.
Lets take the above example and look at some code that demonstrates what I'm trying to do -
Mediator
'use strict';
class Mediator {
constructor () {
this._list = {};
}
subscribe (eventName, cb) {
if (!this._list[eventName]) {
this._list[eventName] = [];
}
this._list[eventName].push(cb);
};
trigger (eventName, data) {
let subscribers = this._list[eventName] || [];
for (let i = 0, len = subscribers.length; i < len; ++i) {
let currSubscriber = subscribers[i];
if (Array.isArray(data)) {
currSubscriber.apply(null, data);
} else {
currSubscriber(data);
}
}
}
}
module.exports = Mediator;
Notebook
this.mediator.subscribe('evt.note.completed', this.noteCompleted);
Statusbar
this.mediator.subscribe('evt.note.completed', this.noteCompleted);
Note
this.mediator.trigger('evt.note.completed', note);
Is this a variation of the observer pattern? Is there a better pattern than this to handle my use case?
Aucun commentaire:
Enregistrer un commentaire