Reputation: 53526
Consider the code below :
function createFoo() {
var val;
function Foo() {}
Object.defineProperty(Foo.prototype, 'foo', {
get: function () {
return val;
},
set: function (value) {
val = value;
document.write('foo value set to : ', value);
}
});
return new Foo();
}
var foo = createFoo();
Object.observe(foo, function (changes) { document.write(changes); });
foo.foo = 'bar';
Why is it that Object.observe
's handler is never fired? Can an object prototype be "observed"?
(Please, answers must not suggest to use some kind of third party library.)
Update
Please, read the comments for more information and for the resolution to this problem.
Upvotes: 3
Views: 155
Reputation: 27460
This
foo.foo = 'bar';
does not modify neither foo object nor its prototype thus observe does not report anything.
Here is the version that triggers observer on this.val = value;
:
function createFoo() {
function Foo() {}
Object.defineProperty(Foo.prototype, 'foo', {
get: function () {
return this.val;
},
set: function (value) {
this.val = value;
document.write('foo value set to : ', value);
}
});
return new Foo();
}
var foo = createFoo();
Object.observe(foo, function (changes) { document.write("<br>observer:", changes); });
foo.foo = 'bar';
Upvotes: 2