From 7844971304c7004b0f2cc363ee9f4139c3ad36f9 Mon Sep 17 00:00:00 2001 From: igoradamenko Date: Tue, 13 Feb 2018 01:13:32 +0200 Subject: [PATCH] add sub/pub to store --- web/app/common/store.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/web/app/common/store.js b/web/app/common/store.js index add98f3a..f54e2889 100644 --- a/web/app/common/store.js +++ b/web/app/common/store.js @@ -6,13 +6,24 @@ class Store { this.data = {}; + this.listeners = {}; + _instance = this; return _instance; } + onUpdate(key, cb) { + if (!this.listeners[key]) this.listeners[key] = []; + + this.listeners[key].push(cb); + } + + set(key, obj) { this.data[key] = obj; + + if (this.listeners[key]) this.listeners[key].forEach(cb => cb(this.data[key])); } get(key) { @@ -20,7 +31,6 @@ class Store { } addComment({ text, id, pid }) { - const comments = this.data.comments; const newComment = { comment: { id, @@ -70,11 +80,11 @@ class Store { return root; }; - this.data.comments = this.data.comments.map(thread => paste(thread, newReply)); + this.set('comments', this.data.comments.map(thread => paste(thread, newReply))); } pasteComment(newComment) { - this.data.comments = [newComment].concat(this.data.comments); + this.set('comments', [newComment].concat(this.data.comments)); } replaceComment(newComment) { @@ -89,12 +99,14 @@ class Store { return thread; } - thread.replies = thread.replies.map(reply => replace(reply, comment)); + if (thread.replies) { + thread.replies = thread.replies.map(reply => replace(reply, comment)); + } return thread; }; - this.data.comments = this.data.comments.map(thread => replace(thread, newComment)); + this.set('comments', this.data.comments.map(thread => replace(thread, newComment))); } getPinnedComments() {