user4747724
user4747724

Reputation:

why is my object returning undefined?

in my document ready function I created an object videoList, and when I inspect and step through the code the object does in fact exist for a short time. However, shortly after its creation it is being returned as not defined by another function. My code looks like:

$(document).ready(function(){
    var videoList = new Object();
    videoList.videoPlaylist = [];
    videoList.addNew = function(data){
        $('.videoPlayer iframe').first().remove();
    }
    videoList.removeOld = function(){

    }

});

This is sitting in a file called video.js. In another file, buffer.js, which loads after video.js and isn't included in the ready function I have:

function loadTracks(playlistID){
    if(GoogleAuth.currentUser.get().hasGrantedScopes(SCOPE)){
         var request = gapi.client.request({
             'method':'GET',
             'path':'/youtube/v3/playlistItems',
             'params':{
                'playlistId':playlistID,
                'part':'snippet',
                'maxResults':'15',
                'key':'AIzaSyD0OY6xhl9gP9CmPXvU-rN-purRDaTrip8'
             }
         });
        request.execute(function(response){
            $('.playlistContainer').html('');
            response.items.forEach(function(element){
                $('.playlistContainer').append('<div class="songTrack"><img src="'+element.snippet.thumbnails.medium.url+'"/><span data-videoId = "'+element.snippet.resourceId.videoId+'">'+element.snippet.title+'</span></div>');
            });

            $('.songTrack').click(function(){
                var data = $(this).data('videoid');
                videoList.addNew(data);
                console.log('I was clicked');
            });
            console.log(response);
        });
    }
}

The gist of this is, it is adding a list of videos to a container and each should be clickable. The videoList object will eventually hold a large list of videos and the addNew and removeOld will handle the arrays upkeep. I'm still learning about objects but from what I gather shouldn't the videoList object be in the global scope and accessible to the loadTracks() function?

Upvotes: 3

Views: 3464

Answers (1)

fanfavorite
fanfavorite

Reputation: 5199

I think the problem is that you are declaring the variable inside the jQuery function scope, rather than globally outside of document ready. Try something like:

var videoList = new Object();
$(document).ready(function(){
   ...
});

Upvotes: 5

Related Questions