1

So I'm pretty new to javascript and don't really understand how the require() function works. What I would like to do, is to set the returnedLibrary global variable. The problem is, if I create a function around the require() method, then the returnedLibrary global variable will not be set.

If I left the outer function block (checkPlaylist()) then the global variable will be set, but the require() method will run on the .js load, not when I would like to call it.

var returnedLibrary;
function checkPlaylist(){
require(['$api/library#Library'], function(Library) {
  returnedLibrary = Library.forCurrentUser();
  returnedLibrary.playlists.snapshot().done(function(snapshot) {
    for (var i = 0, l = snapshot.length; i < l; i++) {
      var playlist = snapshot.get(i);
      // do something with playlist
    }
  });
});
}

Related question: If I have a function inside the require() method, how can I access it?

Thank you for your answers.

Thorasine
  • 11
  • 1
  • 1
    It's not a scope problem, it's a timing issue. The callback passed to `require` is executed some time in the future. Check out [Why is my variable undefined after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/218196) – Felix Kling May 21 '14 at 19:25

0 Answers0