abdul-wahab
abdul-wahab

Reputation: 2272

Google Chrome Developer Tools - Globally Watching a Variable

I need to trace the code that changes the property of an object. Breakpoints in Google Chrome DevTools are set upon line numbers; but in this particular scenario I don't know the code that manipulates the object in application flow, hence can't apply watch expressions over lines.

Is there a way that I can watch a variable in application scope regardless of lines of code?

Please not that I need to find the location in source code where an objects property gets changed not "when" or "what" a change applied.

Upvotes: 1

Views: 513

Answers (2)

Yury Semikhatsky
Yury Semikhatsky

Reputation: 2334

You can define property accessor functions and set breakpoints in them. See defineSetter for more details.

var o = {};
Object.defineProperty(o, 'value', {
  set: function(val) {
    this._value = val;
    console.log(val);
  }
});
o.value = 5;

Upvotes: 1

sdabet
sdabet

Reputation: 18670

The Object.prototype.watch() provides a way to have a callback function executed when a property of an object changes.

From the MDN documentation:

var o = { p: 1 };

o.watch('p', function (id, oldval, newval) {
  console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval);
  return newval;
});

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

o.unwatch('p');
o.p = 5;

outputs:

o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from undefined to 4

Also, ECMAScript 7 will provide a more advanced Object.observe() function: see https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/observe

Upvotes: 2

Related Questions