Circular reference parent-child is undefined unless console.log is called

只谈情不闲聊 提交于 2019-12-12 17:08:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!