javascript - Google 跟踪代码管理器使用什么模式来观察 `dataLayer` 数组?

标签 javascript arrays observer-pattern key-value-observing google-tag-manager

我观察了 dataLayer 数组,但没有看到 push 发生任何变化。实际上根本没有自定义方法。 GTM如何观察数组的变化?据我所知,对 Array 的更改不会引发任何事件,不是吗?


编辑:

我做了更多研究,发现 Google 的用于与 dataLayer 交互的库:https://github.com/google/data-layer-helper#listening-for-messages
我会看一下代码,如果我了解内部工作原理,甚至可能会回答我自己的问题。

最佳答案

GTM 使用的模式是发布/订阅者

代码中的一些细节有助于识别它:https://github.com/google/data-layer-helper/blob/master/src/helper/helper.js 的第 76 行和 181 行

最后是第 114 行和第 119 行

// Add listener for future state changes.
  var oldPush = dataLayer.push;
  var that = this;
  dataLayer.push = function() {
    var states = [].slice.call(arguments, 0);
    var result = oldPush.apply(dataLayer, states);
    that.processStates_(states);
    return result;
  };

查看 states 变量以及它如何传递给 this.processStates_()

关于javascript - Google 跟踪代码管理器使用什么模式来观察 `dataLayer` 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906754/

相关文章:

javascript - jQuery 获取文档中的所有 href url 并 chop 或拆分它们

javascript - JS 如何将序列化对象转换为数组?

arrays - 在 go 中解析简单值的 xml 数组

arrays - 二维阵列打印作为引用

java - 这是使用接口(interface)回调的正确方法吗?

java - "Deprecating the Observer Pattern"——其他语言的代码示例?

javascript - 在 Angular UI 网格中显示数据

javascript - AjaxSubmit with window.location on response

arrays - 使用文件名列表填充和读取数组

javascript - 为什么在对 RxJs Subject 调用 complete() 之后我不能再调用 next() 了?