1

I want to declare a object in a js file like: var o = {p:1};

and then create a watch for it in my html file.

  <script>

  var o = {p:1}; 

  o.watch("p",function (id, oldval, newval)
  { 


  alert(newval);
  return newval; 
  }); 

  o.p=count;
  </script>

this code works in my html but if I declare "var o' in my js file it does not work. The reason I want to do that is because a I want to modify the value of my object in my js file and detect it in the html.

3
  • 1
    You had better post your whole html code too Commented Jun 30, 2012 at 5:54
  • write under <script> tag or in .js file is similar. are you adding <script> in .js file Commented Jun 30, 2012 at 6:06
  • ...and while you're at it, you might as well include your whole CSS code. Commented Jun 30, 2012 at 6:07

1 Answer 1

1

The only approach I can think of to track changes to object vars is to use a setter func instead of updating the value directly:

<script type="text/javascript">
  var o = { 
    p:1,
    q:0,
    watches: [],
    setProp: function(prop, newVal) {
      var oldVal = this[prop];
      this[prop] = newVal;
      if(typeof(this.watches[prop]) == 'function')
      {
         this.watches[prop](prop, oldVal, this['prop']);
      }
    }
  }; 

  o.watches["p"] = function (id, oldval, newval) {
    alert(newval);
    return newval; 
  }; 

  o.setProp('p', count);
  o.setProp('q', 0 - count);
</script>

This is about the simplest thing I can come up with, though you'd probably want to add some better error-checking or maybe an addWatch(prop, func) method to o.

Sign up to request clarification or add additional context in comments.

1 Comment

nb: this isn't very secure or reliable code. I wouldn't use it in production as-is but gives you an idea :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.