0

I am building a javascript remote for Kodi, where i only send data if it is changed. I am stuck with this peace of code. It will check every x seconds for a value but i only want to do something if the value has changed. Can someone shed some light on this?

every((0.35).second(), function() {
  var kodi_api_request = {"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1};
  var kodi = encodeURIComponent(JSON.stringify(kodi_api_request));
  var previous = {};
  var stuff = request
  .get('http://localhost:8080/jsonrpc?request=' + kodi, function (error, response, data) {
    var newdata = data
    if (previous !== newdata) {
      console.log('changed');
      previous = newdata;
      console.log(newdata);
    } else {
      console.log('Error!');
    }
  });
});
bartpeperkamp
  • 49
  • 1
  • 14
  • 1
    Looks like the data is a complex object, you'll have to check each property and see if equals. – Shadow The GPT Wizard Dec 27 '15 at 13:41
  • Well, the object i am getting back is this: {"id":1,"jsonrpc":"2.0","result":[{"playerid":1,"type":"video"}]} Not too complex... – bartpeperkamp Dec 27 '15 at 13:43
  • 1
    And you need to compare only the `.id` attribute, i.e. it's unique? If so just change to `if (previous.id !== newdata.id) {` would work. – Shadow The GPT Wizard Dec 27 '15 at 13:48
  • I was just going to say, perhaps `id` would be sufficient, if it really is unique. – T.J. Crowder Dec 27 '15 at 13:48
  • First, in order to save the preveious value, the variable `previous` must be global. You can achieve this like this : window.previous = {}; // must be done once before your function Or, you can do this in you function : window.previous = window.previous || {}; // create it if it doesn't exists – ikken Dec 27 '15 at 13:55
  • @ikken wrong. The scope is just fine in the posted code sample, no need to make it part of window. – Shadow The GPT Wizard Dec 27 '15 at 14:08
  • @Shadow Wizard . by declaring the variable `var previous = {};` like in the post, it supposes that previous will be initialized every time the callback of function `every` is called. So, the previous value will be lost – ikken Dec 27 '15 at 14:22
  • @ikken that's the whole point, that the previous value will be lost and overwritten with the current value. Unless I'm way off here and you can come with a proof I'm wrong, I can't see anything wrong with the scope. – Shadow The GPT Wizard Dec 27 '15 at 14:26
  • All local variables of function `every((0.35).second(), function() {` are destroyed at the end of evry execution. So, nothing is saved for the next exeuction. It is the basic definition of local variables – ikken Dec 27 '15 at 14:48
  • Thanks for the answers! Comparison is working, however, the whole thing indeed gets executed every x seconds so it always will run the whole thing. This way it is not going to work. – bartpeperkamp Dec 27 '15 at 16:09

0 Answers0