问题
Please consider the following code
var factory = function (element, opts) {
var MutationObserverController = function (element, opts) {
var defaults = {
subtree: true,
childList: true,
characterData: true
};
this.options = $.extend({}, defaults, opts);
this.watchedElement = element;
this.observer = new MutationObserver(this.mutationObserver);
this.observer.context = this;
//console.log(this.observer); //->THIS LINE
};
MutationObserverController.prototype.connect = function () {
this.observer.observe(this.watchedElement, this.options);
};
MutationObserverController.prototype.disconnect = function () {
this.observer.disconnect();
};
MutationObserverController.prototype.mutationObserver = function (mutations, observerObj) {
var ctx = observerObj.context;
ctx.disconnect();
mutations.forEach(function (m) {
console.log(m);
});
ctx.connect();
};
return new MutationObserverController(element, opts);
};
var mutOb = factory($('#myEditor').get(0), {});
mutOb.connect();
This code is triggered everytime a DOM modification (mutation) is done in a contenteditable div and it prduces an error stating that observerObj.context is undefined.
However, if I uncomment this line //console.log(this.observer); //->THIS LINE
, no error is produced and it works as expected.
Why?
Here's the JSFiddle. To reproduce, press ENTER in the contenteditable div, after the text.
Note: If someone has a suggestion in how to pass context to the mutationObserver without a circular reference (or give the correct scope), I would be grateful too.
回答1:
You can use Function#bind to keep correct this
:
this.observer = new MutationObserver(this.mutationObserver.bind(this));
Try it: http://jsfiddle.net/reLr9/
来源:https://stackoverflow.com/questions/14730172/circular-reference-parent-child-is-undefined-unless-console-log-is-called