Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

346
Views
Listening to changes made to a variable (for real)

I have the following situation:

  • I have two Vanilla JS components.
  • The first component, Alpha, can make changes to a window variable, e.g. window.App.messages.
  • The second component, Beta, needs to execute a given function but only after window.App.messages has changed.

We have the following constraints:

  • [A] We don't want the two components to communicate to each other in any other way other than through window.
  • [B] We don't want Beta to change window.App.messages in any way.
  • [C] window.App.messages should be agnostic with regards to which component is going to set and get its data.

I found a number of relevant Stack Overflow threads, but they all seem to suggest solutions that don't actually work to solve this use case. Specifically:

  • Use Proxy (example 1, example 2). The problem with Proxy is that you then need to listen to changes to the proxy and not the original object. This implementation wouldn't work as it would require Alpha and Beta to communicate directly. It breaks [A].
  • Overwrite setters and getters via defineProperty (example). This solution requires Beta to change the original object and that's not okay. It breaks both [B] and [C].
  • Create the object with custom setters and getters. This too doesn't work since it breaks [C].

What I would need is something like this:

var window.App.messages = ["Hello, world!"];

function logChange(variable) {
  console.log(`New value: ${variable.at(-1)}`)
};

var varListener = Listener(window.App.messages, logChange);

window.app.messages.push("The answer is 42.");

>> New value: The answer is 42.
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!