Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4838

Initializer + service + util Google Tag Manager

$
0
0

@kimek wrote:

Hi Guys,

I have just question about design of util as ember object, using it in service and injecting this service in instance initializer.

Is this is ok ? I’m a little worried about serving util as ember object…

Most of the GTM code is thanks to https://gist.github.com/pwfisher from https://gist.github.com/pwfisher/5fd09ec2ccab253008f9

I just add wrappers, service and remove GTM snipet from util as I prefer to add it in index.html directly.

//instance initializer

export default {
  name: 'gtm-wrapper-init',
  initialize: function (container) {
    let router = container.lookup('router:main'),
        gtm = container.lookup('service:gtm');
    router.on('didTransition', function () {
      gtm.get('gtmUtil').trackPageView(this.get('url'));
    });
  }
}

//gtm-util

import EmberObject from '@ember/object';

export default EmberObject.extend({
  defaultEvent: {
    event: 'trackEvent',
    eventCategory: '',
    eventAction: '',
    eventLabel: '',
    eventValue: ''
  },
  defaultPageView: {
    event: 'vpv',
    virtualPagePath: ''
  },

  createPayload: function (type, o) {
    let data = o || {},
        defaultPayload = this['default' + type],
        payload = {};
    Object.keys(defaultPayload).forEach(function (key) {
      payload[key] = data.hasOwnProperty(key) ? data[key] : defaultPayload[key];
    });
    return payload;
  },

  trackEvent: function (o) {
    window.dataLayer.push(this.createPayload('Event', o));
  },

  trackPageView: function (path) {
    window.dataLayer.push(this.createPayload('PageView', { virtualPagePath: path }));
  }

});

// gtm service

import Ember from 'ember';
import gtmUtil from '../utils/gtm-util';

export default Ember.Service.extend({
  init() {
    if (!this.get('gtmUtil')) {
      this.set('gtmUtil', gtmUtil.create());
    }
  },
});

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 4838

Trending Articles