Custom event document onContentChange

前端 未结 2 466
小蘑菇
小蘑菇 2021-01-19 07:18

Here jsFiddle to test sample

I\'m currently writing a jquery snippet to handle any html content change in DOM \'triggered\' by any jquery domManip function (extendin

2条回答
  •  心在旅途
    2021-01-19 08:02

    I come with slightly modified version wich seems to work fine for the purpose i reach. Need optimization for the .on() method extend, so please feel free to share your feedbacks.

    Inspired from here: https://groups.google.com/forum/?fromgroups=#!topic/jquery-dev/ZaMw2XB6wyM

    Thanks to Wil Stuckey

    Here jsFiddle

    ;(function ($) {
        var fctsToObserve = {
            append: [$.fn.append, 'self'],
            prepend: [$.fn.prepend, 'self'],
            remove: [$.fn.remove, 'parent'],
            before: [$.fn.before, 'parent'],
            after: [$.fn.after, 'parent']
        }, fctsObserveKeys = '';
        $.each(fctsToObserve, function (key, element) {
            fctsObserveKeys += "hasChanged." + key + " ";
        });
        var oOn = $.fn.on;
        $.fn.on = function () {
            if (arguments[0].indexOf('hasChanged') != -1) arguments[0] += " " + fctsObserveKeys;
            return oOn.apply(this, arguments);
        };
        $.fn.hasChanged = function (types, data, fn) {
            return this.on(fctsObserveKeys, types, null, data, fn);
        };
        $.extend($, {
            observeMethods: function (namespace) {
                var namespace = namespace ? "." + namespace : "";
                var _len = $.fn.length;
                delete $.fn.length;
                $.each(fctsToObserve, function (key) {
                    var _pre = this;
                    $.fn[key] = function () { 
                        var target = _pre[1] === 'self' ? this : this.parent(),
                            ret = _pre[0].apply(this, arguments);
                        target.trigger("hasChanged." + key + namespace, arguments);
                        return ret;
                    };
                });
                $.fn.length = _len;
            }
        });
        $.observeMethods()
    })(jQuery);
    

提交回复
热议问题