views:

33

answers:

2

Here's a simple javascript program:

var $d = {};

var AudioPlayer = function(filename, timeUpdateCallback, playbackDone){
  // An HTML5 audio player is defined here.
}

$d.AudioPlayer = AudioPlayer;

var AudioManager = function(chapterId){
        var audioPlayer;
        var me=this;

        this.next = function(){
               ...
        }

        function playSegment(){

        //      var path='/test.mp3';
                $d.utils.log('Path is: '+path+'');
                audioPlayer = new $d.AudioPlayer(path, function(p){} ,

                        function(){
                            me.next(); 
                        }
                );

                audioPlayer.play();
        }
}

When the playback done callback is called in a desktop browser (safari/ firefox) everything works fine. However, when using the exact same javascript in iPhone Safari, I see an exception "could not find variable me".

Why is there a difference in the way closures are handled? Is there anyway to get around this?

Update: I have failed to mention that the audioPlayer relies on PhoneGap's media class; which does not accept closures in its callbacks. The problem is that the callback is stored as a string in native code, so when it returns the reference is gone. For desktop browsers i was actually using and HTML5 audio tag, so I didn't ecounter this issue.

+1  A: 

What version of mobile safari are you using?

I captured the essence of your code thus:

var d = {

 AudioPlayer: function (filename, timeUpdateCallback, playbackDone){
    document.write ("Audioplayer<br/>");
    return {
      play : function () {playbackDone && playbackDone ();}
    } 
  }
};  

try {
  (function AudioManager (chapterId) {
    var me = this;

    this.next = function (){
      document.write  ("AudioManager next<br/>");
    }

    function playSegment (){
      var audioPlayer = new d.AudioPlayer ('/test.mp3', function(p){} ,
        function () {
          document.write  ('playbackdone<br/>');
          me.next (); 
        }
      );

      audioPlayer.play();
    }

    playSegment ();
  }) ();
} catch (e) {
  document.write(e);
}

And it runs without error on Chrome, iPod touch and iPad.

Hans B PUFAL
Hi, see my update above, which explains the difference. Thanks for taking the time of answering though +1.
jd
A: 

I had failed to mention that the audioPlayer relies on PhoneGap's media class; which does not accept closures in its callbacks. The problem is that the callback is stored as a string in native code, so when it returns the reference is gone. For desktop browsers i was actually using and HTML5 audio tag, so I didn't ecounter this issue.

jd