0

I currently have a multi-client application running in NodeJS with a Knockout, HTML, JS front-end. I have some fields on the page with Knockout subscriptions so that when a user makes a change, it is sent to the server and then broadcasted to the server.

this.Name.subscribe(function(newValue) {
      Helpers.SendUpdate(this._id, "resources", { "Name": newValue });
}, this);

The other clients get the messages fine and then update the fields as needed but my problem is that the when the field is updated by the system it triggers another update to be sent to the server as the subscription is triggered and all kinds of cyclic badness insues.

Is there a clever way you guys can think of knowing if an action is triggered by the user or the system?

Jareth
  • 431
  • 1
  • 3
  • 16

2 Answers2

0

You could store whether the app is processing a server update in another variable and check this state in your subscriber:

var VM = function() {
  
  this.someObs = ko.observable(0);
  this.inServerUpdate = false;

  this.serverUpdate = function() {
    this.inServerUpdate = true;
    this.someObs(Math.round(Math.random() * 100));
    this.inServerUpdate = false;
  }.bind(this);

  this.someObs.subscribe(function(val) {
    if (!this.inServerUpdate) {
      console.log("Post", val, "to server");  
    }
  }, this);
}

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input data-bind="value: someObs">
<button data-bind="click: serverUpdate">mimic server update</button>
user3297291
  • 22,592
  • 4
  • 29
  • 45
0

Thought about using a flag on the object to check if it was updating but found that the update happened so quickly that when the subscriber got to checking the flag it had already been set back.

Ended up with a hybrid approach:

Firstly I added a unique session id to a request to know which client the update came from. This meant that when a message was broadcast, the client could ignore it.

Secondly i used the solution linked below to perform a silent update and ensure that the subscribe wasn't kicked off again.

Change observable but don't notify subscribers in knockout.js

Community
  • 1
  • 1
Jareth
  • 431
  • 1
  • 3
  • 16