I am writing a simple chat using Node.js, Websockets and Vue.js. Specifically, I have a Vue instance and a Websockets Client. When a user presses a "Submit" button, Vue asks the Client to send a message to a Server. When the Client receives a message from the Server, it asks the Vue to render it to the page. My first thought was for the Vue to have a reference to Client, and for Client to have a reference to Vue, but the two objects become closely coupled. Is there a better way to enforce communication between these two objects?

  • You don't need to hold two references; you only need to hold one. – Robert Harvey Mar 9 '19 at 19:03
  • Could you please provide some code? What did you try? Without details your issue sounds very abstract. However, I would use something like mediator pattern. It means you may have object that hold both references. – Alex Gurskiy Mar 9 '19 at 21:30
  • The Client only needs a "callback" to call after each server notification. The callback could be a standalone component or a Vue controller's method. client.onEvent("xxx",callback()) or client.onEvent("xxx", function(message){ }) – Laiv Mar 11 '19 at 14:40

You can use Observer pattern.

  • The Vue instance holds the reference to a Client instance.
  • The Client instance is observed by an ClientObserver instance. The Client instance will push new event to its observer when it receive updates from the server.
  • The Vue instance subscribes to the ClientObserver instance so that it will re-render every time a new event comes.

In this case, the Vue instance only keeps one reference to the Client instance and the Client instance only keeps on reference to the ClientObserver instance.

  • It could be worthwhile to consider both the inputs and outputs of the Client as reactive streams, in any case. So that rather than your Vue needing to know exactly how to tell it to send something, anything that needs to push to the server just shoves something on an observable, in the same way things watch an observable to get the updates – Delioth Mar 11 '19 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.