将事件列表添加到DOM元素(如果存在)

时间:2019-01-26 17:41:27

标签: javascript addeventlistener tealium

我正在尝试将Eventlistner添加到变量更改时触发的变量,这里的问题是该变量在加载时不存在,但仅当有人启动嵌入式youtube视频时才可用。

// Tealium Tracking Code for YouTube iframe embeds
//
// Read the identifiers on the YouTube iframes. If not present, then add ids
if (jQuery('iframe[src*="youtube.com"]').length > 0) {
 var i = 0, id;
 window.iframe_id = [];
 jQuery('iframe[src*="youtube.com"]').each(function() {
   if (jQuery(this).attr('id')) {
     id = jQuery(this).attr('id');
     window.iframe_id.push(id);
   } else {
     id = 'tealium_youtube' + i;
     jQuery(this).attr('id', id);
     window.iframe_id.push(id);
     i++;
   }
 });
}

// Configure Milestones
//
function setMileStones(i) {
  // Set the intervals here as you want them reported, in % viewed, each number separated by a comma
  // If you do not want mileStones set mileStones[i] = [] ;
  mileStones[i] = [10, 25, 50, 75, 90];
}
var mileStones = [];
for (i = 0; i < window.iframe_id.length; i++) {
  setMileStones(i);
}

// Load the YouTube iframe library
//
var ytapi = document.createElement('script');
ytapi.src="https://ww" + "w.youtube" + ".com/iframe_api";
var scriptref = document.getElementsByTagName('script')[0];
scriptref.parentNode.insertBefore(ytapi, scriptref);

window.players = [];
window.onYouTubeIframeAPIReady = function() {
  // Confirm existing ID or set ID in the iframe for each video on the page
  jQuery('iframe[src*="youtube.com"]').each(function() {
  var id = jQuery(this).attr('id');
  window.players[id] = new YT.Player(id, {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
      }
    });
  });
};

window.start = [];
window.onPlayerReady = function(event) {
 //Log that the video is ready/open
 var idx;
 for (i = 0; i < window.iframe_id.length; i++) {
   if (window.iframe_id[i] === event.target.a.id) {
     idx = i;
   }
   window.start.push(true);
 }
 if (event.target.getPlayerState() === YT.PlayerState.CUED) {
   var player = event.target;
   utag.link({
     tealium_event: 'video_load',
     video_id: player.j.videoData.video_id,
     video_length: player.getDuration(),
     video_name: player.j.videoData.title,
     video_platform: 'YouTube'
   });
  }
};

var playerCheckInterval;

window.onPlayerStateChange = function(event) {
 player = event.target;
 var playhead, idx;
 for (i = 0; i < window.iframe_id.length; i++) {
   if (window.iframe_id[i] === event.target.a.id) {
     idx = i;
   }
 }

 tealium_event = "";

 if (event.data == YT.PlayerState.PLAYING) {
   if (start[idx]) {
     if (mileStones[idx].length > 0) {
       playerCheckInterval = setInterval(mileStoneCheck, 50);
     }
     tealium_event = "video_start";
   } else {
     //This will catch when the video playback is changed from not playing to playing
     tealium_event = "video_play";
     playhead = player.getCurrentTime().toString();
   }
   start[idx] = false;

 } else if (event.data == YT.PlayerState.PAUSED) {
   tealium_event = "video_pause";
   playhead = player.getCurrentTime().toString();

 } else if (event.data == YT.PlayerState.ENDED) {
   if (mileStones[idx].length > 0) {
     clearInterval(playerCheckInterval);
     // reset in case visitor replays the video
     playerCheckInterval = 0;
     setMileStones(idx);
   }
   tealium_event = "video_complete"; // utag
 }

 if (tealium_event) {
   utag.DB("Video event: " + tealium_event + ", video ID: " + window.iframe_id[idx]);
   utag.link({
     tealium_event: tealium_event,
     video_playhead: parseInt(playhead),
     video_id: player.j.videoData.video_id,
     video_length: player.getDuration(),
     video_name: player.j.videoData.title,
     video_platform: 'YouTube'
   });
 }

  function mileStoneCheck() {
    var idx;
    for (i = 0; i < window.iframe_id.length; i++) {
      if (window.iframe_id[i] === player.a.id) {
        idx = i;
      }
    }
    var duration = player.getDuration();
    var playhead = player.getCurrentTime();
    var percComplete = (playhead / duration) * 100;
    var ms_len = mileStones[idx].length;
    if (ms_len > 0) {
      var next_ms = mileStones[idx][0];
      if (next_ms <= percComplete) {
        mileStones[idx].shift();
        utag.DB("Video event: video_milestone, video ID: " + window.iframe_id[idx] + ", Milestone=" + percComplete.toFixed());
        utag.link({
          tealium_event: 'video_milestone',
          video_playhead: parseInt(playhead),
          video_id: player.j.videoData.video_id,
          video_length: parseInt(duration),
          video_milestone: next_ms.toString(),
          video_name: player.j.videoData.title,
          video_platform: 'YouTube'
        });
      }
    }
  }
};

我要监视的变量为var player,该变量仅在触发回调后才可用。

是否存在在变量上添加eventlistner的方式?

我尝试了类似的方法

window.onload = function () {

   if (typeof player !== "undefined")
   {
      doSomething();
   }

}

但是,这似乎并不能监视播放器何时变为“可用” =>从哪里可以添加事件侦听器。它似乎只运行一次,即在加载窗口时。

1 个答案:

答案 0 :(得分:0)

我认为您可以在更改变量的值后调用该函数。

可能的代码示例:

window.onPlayerStateChange = function(event) {
  player = event.target;
  var playhead, idx;
  for (i = 0; i < window.iframe_id.length; i++) {
    if (window.iframe_id[i] === event.target.a.id) {
      idx = i;
    }
  }
  ...
  // the player var changes here so just call what you need here like
  doSomething(player);
}