草庐IT

javascript - 重新连接和断开 MutationObserver

coder 2024-07-15 原文

本题为this的续题一。但是,没有必要阅读前面的内容,我只是为感兴趣的读者提供一个链接。

正如@Shomz 所建议的,有一个观察者,它将对具有某个类的每个元素使用react:

var target = document.querySelectorAll(".someclass");
for (var i = 0; i < target.length; i++) {
    create(target[i]);
}

function create(t) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var foo = t.getAttribute("aaa")
            if (foo == "vvv")
                t.style.backgroundColor = "red";
        });
    });

    var config = {
        attributes: true
    };

    observer.observe(t, config);
}

因此,有两个紧密交织的问题。

1)由于某些原因,观察者可能会断开连接。我怎样才能重新连接它?我尝试使用 observer.observe,但它在这里不起作用。

2) 第二个问题,手动断开观察者的方式是什么?我尝试使用 observer.disconnect();,但它也不起作用。

最佳答案

实际上,您不必使用多个实例来观察多个 DOM 节点元素。
您可以使用一个突变观察器来观察多个 DOM 节点元素。
要在断开连接后重新连接观察者,您不必重新创建突变观察者的新实例,只需再次调用已创建实例上的 observe 方法即可,但前提是它已经已断开连接。

disconnect()

Stops the MutationObserver instance from receiving notifications of DOM mutations. Until the observe() method is used again, observer's callback will not be invoked.

调用 observe()已经被观察的元素上的方法不会对观察产生任何影响。至少如果您使用相同的观察者实例进行观察。

NOTE: Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it.

这是一个使用一个观察者实例观察几个图像元素的宽度属性的例子。该示例使用超时为每个图像宽度属性设置一个随机值。回调函数将输出更改并断开观察者,然后重新开始整个过程​​。

var imgs = Array.prototype.slice.call( document.images ),
    config = { attributes: true, attributeOldValue: true },
    observer = new MutationObserver( mutationCallback );

function mutationCallback ( mutations ) {
  mutations.forEach(function( record ) {
    record.target.previousElementSibling.textContent = "";
    record.target.previousElementSibling.textContent = "The image "
      + record.attributeName 
      + " attribute changed from " 
      + record.oldValue 
      + " to " 
      + record.target.getAttribute('width')
      + ".";
  })
  observer.disconnect();
  startObserving( imgs );
}

function changeNodeAttr ( attr, nodes ) {
  window.setTimeout(function() {
    nodes.forEach(function( node ) {
      node.setAttribute( attr, Math.floor( Math.random()*( 300 - 100 + 1 ) +100 ) );
    })
  }, 2500)
}

function startObserving ( nodes ) {
  nodes.forEach(function( node ) {
    observer.observe( node, config );
  })
  changeNodeAttr( "width", imgs );
}

startObserving( imgs );
body {
  font-family: sans-serif;
}

img {
  display: block;
  margin-bottom: 10px;
}
<span></span>
<img class="my-images" src="https://via.placeholder.com/300x100?text=image" width="300">
<span></span>
<img class="my-images" src="https://via.placeholder.com/300x200?text=image" width="300">
<span></span>
<img class="my-images" src="https://via.placeholder.com/300x400?text=image" width="300">

关于javascript - 重新连接和断开 MutationObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35290789/

有关javascript - 重新连接和断开 MutationObserver的更多相关文章

  1. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  2. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  3. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  4. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  5. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

  6. ruby - 我的 Ruby IRC 机器人没有连接到 IRC 服务器。我究竟做错了什么? - 2

    require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame

  7. ruby - 将全局 $stdout 重新分配给控制台 - ruby - 2

    我正在尝试将$stdout设置为临时写入一个文件,然后返回到一个文件。test.rb:old_stdout=$stdout$stdout.reopen("mytestfile.out",'w+')puts"thisgoesinmytestfile"$stdout=old_stdoutputs"thisshouldbeontheconsole"$stdout.reopen("mytestfile1.out",'w+')puts"thisgoesinmytestfile1:"$stdout=old_stdoutputs"thisshouldbebackontheconsole"这是输出。r

  8. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  9. ruby-on-rails - 连接字符串时如何在 <%=%> block 内输出 html_safe? - 2

    考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://

  10. ruby - Faye WebSocket,关闭处理程序被触发后重新连接到套接字 - 2

    我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d

随机推荐