Pergunta

Eu estou tentando criar um evento especial jQuery que é desencadeada quando o conteúdo que está ligada, muda. Meu método é verificar o conteúdo com um setInterval e verifique se o conteúdo foi alterado desde a última vez. Se você tiver qualquer método melhor de fazer isso, deixe-me saber. Outro problema é que eu não consigo limpar o intervalo. Enfim, o que eu preciso é a melhor maneira de verificar se há alterações de conteúdo com o event.special.

(function(){

    var interval;

    jQuery.event.special.contentchange = {
        setup: function(data, namespaces) {
            var $this = $(this);
            var $originalContent = $this.text();
            interval = setInterval(function(){
                if($originalContent != $this.text()) {
                    console.log('content changed');
                    $originalContent = $this.text();
                    jQuery.event.special.contentchange.handler();
                }
            },500);
        },
        teardown: function(namespaces){
            clearInterval(interval);
        },
        handler: function(namespaces) {
            jQuery.event.handle.apply(this, arguments)
        }
    };

})();

e vinculá-lo como este:

$('#container').bind('contentchange', function() {
        console.log('contentchange triggered');
});

Eu recebo o console.log 'conteúdo mudou', mas não o console.log 'ContentChange desencadeada'. Portanto, é óbvio que o retorno nunca é acionado.

Eu só uso o Firebug para alterar o conteúdo e para disparar o evento, para testá-lo.

Atualizar
Eu não acho que eu fiz este bastante clara, o meu código não realmente funcionar. Eu estou olhando para o que estou fazendo de errado.


Aqui está o código acabado para qualquer pessoa interessada

(function(){

    var interval;

    jQuery.event.special.contentchange = {
        setup: function(){
            var self = this,
            $this = $(this),
            $originalContent = $this.text();
            interval = setInterval(function(){
                if($originalContent != $this.text()) {
                    $originalContent = $this.text();
                    jQuery.event.handle.call(self, {type:'contentchange'});
                }
            },100);
        },
        teardown: function(){
            clearInterval(interval);
        }
    };

})();

Graças à Mushex por me ajudar.

Foi útil?

Solução

também dar uma olhada para James semelhante roteiro (declarando como jquery método de objeto e não como evento)

jQuery.fn.watch = function( id, fn ) {

    return this.each(function(){

        var self = this;

        var oldVal = self[id];
        $(self).data(
            'watch_timer',
            setInterval(function(){
                if (self[id] !== oldVal) {
                    fn.call(self, id, oldVal, self[id]);
                    oldVal = self[id];
                }
            }, 100)
        );

    });

    return self;
};

jQuery.fn.unwatch = function( id ) {

    return this.each(function(){
        clearInterval( $(this).data('watch_timer') );
    });

};

e criando evento especial

jQuery.fn.valuechange = function(fn) {
    return this.bind('valuechange', fn);
};

jQuery.event.special.valuechange = {

    setup: function() {

        jQuery(this).watch('value', function(){
            jQuery.event.handle.call(this, {type:'valuechange'});
        });

    },

    teardown: function() {
        jQuery(this).unwatch('value');
    }

};

De qualquer forma, se você precisar dele apenas como evento, você roteiro é bom:)

Outras dicas


Eu sei que este post / questão é um pouco velho, mas esses dias eu estava atrás de uma solução semelhante e eu encontrei isto:

$('#selector').bind('DOMNodeInserted', function(e) {
    console.log(e.target);
});

Fonte: http: // naspinski .net / post / Monitoramento-a-DOM-elemento-para-Modificação-com-jQuery.aspx

Espero que isso ajuda alguém!

O código acabado na pergunta original funcionou para mim, muito obrigado! Eu gostaria apenas de nota que estou usando jQuery 1.9.1 e US $ .event.handle parece ter sido removido. Mudei o seguinte para obtê-lo para o trabalho.

jQuery.event.handle.call (self, {type: 'ContentChange'});

para

jQuery.event.dispatch.call (self, {type: 'ContentChange'});

talvez você poderia tentar Mutation Observer

Aqui estão o código:

mainArea = document.querySelector("#main_area");
MutationObserver = window.MutationObserver;
DocumentObserver = new MutationObserver(function() {
       //what you want to run
});

DocumentObserverConfig = {attributes: true, childList: true, characterData: true, subtree: true};

DocumentObserver.observe(mainArea, DocumentObserverConfig);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top