Update var - using .change?

Hello!

I have an important question that I’m starting to face on 80% of the cases.

Lets say I have this:

var bcount = properties.count;
bcount.change(function() { favicon.badge(bcount); });

properties.count = its a number that changes depending on the user actions.
favicon.badge its a javascript that shows the action, which is working good.

I tried to use .change on the bcount var, but is giving me error as I supposed because is not an element.
Is there any way to listen a var when value changes?

PS: The problem I’m facing is that when the count gets updated, with a new number. It only updates after refreshing the page.

Thanks!!

JavaScript doesn’t support data binding by default. You have to build it yourself.

1 Like

If properties is an object, it is fairly easy to observe using a Proxy. When a change is detected, you can check if it was the count property that changed and do something.

function observe(o, callback) {
  return new Proxy(o, {
    set(target, property, value) {
      callback(property, value);
      target[property] = value;
    },
  });
}

const properties = { count: 10 };
const obj = observe(properties, (property, value) => {
  if (property === 'count'){
    console.log(`Count changed to ${value}`);
  }
});

obj.count = 100;
// Count changed to 100

obj.count = -1
// Count changed to -1

Ref: https://github.com/GoogleChrome/proxy-polyfill#example

4 Likes

Thanks to both!!
Solved with this:

var bcount = {
  a: properties.count,
  get b() { return this.a; },
  set c(x) { this.a = properties.count; }
};

favicon.badge(bcount.a);

Probably I can optimize a bit more the code, or clean it, but it works :smiley:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.