What is the pattern used by Google Tag Manager in order to observe de `dataLayer` Array?

时光毁灭记忆、已成空白 提交于 2019-12-11 12:43:56

问题


I observed the dataLayer array and I don't see any changes to push. No custom methods at all, actually. How is GTM observing the changes to the array? As far as I know, changes to an Array don't throw any events, do they?


Edit:

I did some more research and found Google's library for interacting with the dataLayer: https://github.com/google/data-layer-helper#listening-for-messages
I'll take a look at the code and maybe even answer my own question if I understand the ineer workings.


回答1:


Pattern used by GTM is publish / subscriber

Some details in code that helps to recognize it: line 76 and 181 of the https://github.com/google/data-layer-helper/blob/master/src/helper/helper.js

And finally line 114 and 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;
  };

Take a look into states variable and how it is passed to this.processStates_()



来源:https://stackoverflow.com/questions/28906754/what-is-the-pattern-used-by-google-tag-manager-in-order-to-observe-de-datalayer

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