1

So is there a way to fire an event when a variable is changed? It doesn't seem like that's possible unless you have something to watch that variable or a method that changes that variable but I've got a program that would be a lot easier to write if this were possible.

In js if you change something like an image DOM objects width property the image width will update automatically. If you change a scrollable objects scrollTop value it will automatically scroll. You don't need to use a setWidth() method or setScroll() method (in most cases).

How does this work? Could I replicated it?

Ex:

    DOM = document.getElementById("testInput"); // text input field
    variable = 10;
    DOM.value = variable;

    variable.onchange = function(val){DOM.value = val;} // ???

    //or possibly

    window.observe(variable, function(val){DOM.value = val;} // ???

Weird stuff I know...

micah
  • 6,213
  • 6
  • 35
  • 62
  • http://stackoverflow.com/questions/1759987/detect-variable-change-in-javascript an earlier question that appears to have your answer. – Ben Barden Feb 29 '12 at 22:33

1 Answers1

0

You should look into jquery, http://www.jquery.com

They allow for a lot of events to be registered to HTML objects by ID or Class. You could find an onchange for pretty much any form input without a problem to put your code into.

Here's the API for it: http://api.jquery.com/change

Developer
  • 1,963
  • 11
  • 11
  • 2
    I know that... If that would have solved the issue I would have done that without asking. My question is for a problem that is the complete opposite of your hypothetical problem. – micah Feb 29 '12 at 22:39
  • I don't think I understand your question then. Did you follow the link that Ben Barden posted? http://stackoverflow.com/questions/1759987/detect-variable-change-in-javascript – Developer Feb 29 '12 at 22:46
  • Ok I see. So it looks like there really isn't anything I can do except write setter and getter methods. That's dissapointing but at least I could verify that. Thanks! – micah Feb 29 '12 at 23:07