0

I hope not to bother anyone. I don't have enough reputation points to comment and ask directly in that beautiful suggestion: https://stackoverflow.com/a/37403125/8261024 .

My additional question to that great solution is: what, if I want to detect only real changes? What I mean is: if the value of x.a changes, i will know. What, if the value of x.a was 42 and after the change it is 42 too, but I want only a real change of the value? I only want to know, if it changes to dolphin or fish or sth.

Maybe I am blind right know so I can't see the obvious.

Thanks.

VDWWD
  • 32,238
  • 19
  • 56
  • 70
Olafant
  • 803
  • 1
  • 5
  • 15

1 Answers1

1

Yes shure, simply compare the new to the stored value:

var obj = (function(){
  let store = undefined;

  return {
   get value() {
     return store;
   },
   set value(v){
    if(v !== store){
      alert("changed");
      store = v;
    }
   },
  };
})();

obj.value = 10;//changed
obj.value = 10;
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • Let's say, I use this and my name for the object is infoText instead of obj and my code is [code] var infoText = { aInternal: oldInfoText, aListener: function(val) {}, set text(val) { this.aInternal = val; this.aListener(val); }, get text() { return this.aInternal; }, registerListener: function(listener) { this.aListener = listener; } } infoText.registerListener(function(val) { alert("Someone changed the value of infoText to " + val); }); [/code] – Olafant Jul 05 '17 at 21:06
  • @ilafant please underatand the upper code. Its quite similar to yours and you will he able to change yours easily. Btw mys is better... – Jonas Wilms Jul 06 '17 at 07:56
  • 1
    you're right. Thank you very much for your help. As I said: I was a little blind the other night. – Olafant Jul 08 '17 at 08:46