From bc0899665ecab7b5a9037d5dd3a6b4ae264401a9 Mon Sep 17 00:00:00 2001 From: qubird Date: Sat, 18 Apr 2015 09:37:30 +0100 Subject: [PATCH] Do not destroy and create new player on video change. Fix for https://github.com/brandly/angular-youtube-embed/issues/46. Instead of creating a new player, use the current one when it's already existing, loading the new video via YT method loadVideoById --- src/angular-youtube-embed.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/angular-youtube-embed.js b/src/angular-youtube-embed.js index 21ae316..38d8207 100644 --- a/src/angular-youtube-embed.js +++ b/src/angular-youtube-embed.js @@ -185,13 +185,33 @@ angular.module('youtube-embed', ['ng']) return player; } + function isEmpty (obj) { + if (obj == null) return true; + if (Object.keys) return Object.keys(obj).length == 0; + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + return keys.length == 0; + }; + function loadPlayer () { - if (scope.videoId || scope.playerVars.list) { - if (scope.player && scope.player.d && - typeof scope.player.destroy === 'function') { - scope.player.destroy(); + // If the player is still on the page, as well as the iframe containing it + if (scope.player && !isEmpty(scope.player) && scope.player.getIframe()) { + var playerVars = ( playerVars ? playerVars : angular.copy(scope.playerVars) ); + playerVars.start = playerVars.start || scope.urlStartTime; + + if (scope.videoId) { + scope.player.loadVideoById({ + videoId: scope.videoId, + startSeconds: playerVars.start, + }); + } else if (scope.playerVars.list) { + scope.player.loadPlaylist({ + playlist: scope.playerVars.list, + startSeconds: playerVars.start, + }); } - + } else { + // Otherwise, create a new player scope.player = createPlayer(); } };