0

I use the next code for watch changes in javascript object: https://gist.github.com/eligrey/384583

I have a next code for check updates:

var Obj = {
    prop: 0,
    inc: function() {
      this.prop ++;
    }
};

Obj.watch('prop', function(prop, oldv, newv) {
    console.log(prop);
    console.log(oldv);
    console.log(newv);
  });

// on button click i increment prop:

$("#btn").on('click', function() {
    Obj.inc();
});

When i run this code, and click button i get in console:

prop
0 
1

It's correctly.

But, when i click the next time, i get:

z
undefined
NaN

Online demo: http://jsbin.com/jenarapufo/2/edit?html,js,console,output

Why?

1
  • 2
    because u forgot to return new value from watch callback add return newv; Commented Dec 12, 2014 at 12:02

2 Answers 2

2

You need to return new value from watch callback. Update Your handler:

Obj.watch('prop', function(prop, oldv, newv) {
    ...
    return newv;
})
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to return the new value from the callback:

Obj.watch('prop', function(prop, oldv, newv) {
  console.log(prop);
  console.log(oldv);
  console.log(newv);
  return newv;
});

Comments

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.