2012-07-04 53 views
0

我正在處理一個項目,我需要通過方法video.prototype.getCurrentFrame()從播放視頻中返回一個幀數。我的腳本工作得很好,這個方法返回的數字是'未定義的'。我知道我的問題必須做一些與我的變量的範圍,但我是新的JavaScript,我似乎無法使它自己的工作...更新原型變量Javascript

在我的方法video.prototype.setUpPlayer我有一個函數這允許我計算framcount 'timeListener',其中我更新了一個名爲frame的變量; 如果我嘗試通過video.prototype.getCurrentFrame()訪問這個幀變量,它不會達到更新的值。

這裏是我到目前爲止的代碼:

var Video = function(aVideoId){ 
this.videoId = aVideoId; 
this.frame; 
this.videoContainer; 
this.myPlayer; 
this.timeListener; 
this.progressListener; 
}; 

Video.prototype.getCurrentFrame = function(){ 
    return this.frame; 
} 

Video.prototype.setVideoContainer = function(){ 
     videoContainer = $('<div>', { 
     id: this.videoId, 
     class: 'projekktor', 
     width: "100%", 
     height: "100%", 
    }); 
    $('#innerContainer').html(videoContainer); 
} 

Video.prototype.setUpPlayer = function(){ 
    videoId = this.videoId; 


    myPlayer = projekktor('#' + videoId, { 
     controls: "true", 
     volume: 0.5, 
     preload: false, 
     autoplay: true, 
     playlist: [{ 
      0: { 
       src: '/' + videoId + '.mp4', 
       type: 'video/mp4' 
      }, 
      1: { 
       src: '/' + videoId + '.mov', 
       type: 'video/mov' 
      }, 
      2: { 
       src: '/' + videoId + '.ogv', 
       type: 'video/ogv' 
      } 
     }] 
    }, function() { // call back 
     myPlayer.addListener('time', timeListener); 
     myPlayer.addListener('progress', progressListener); 
    }); 

    timeListener = function(duration) { 
      $('#currentTime').html(duration); 
      frame = Math.round(duration * 25); 
      $('#currentFrame').html(frame); 
          return this.frame = frame; 


     } 

    progressListener = function(value) { 
      $('#progress').html(Math.round(value)) 
      $('#progress2').html(myPlayer.getLoadProgress()); 
     } 
} 

預先感謝您的幫助!

+1

如何調用函數'.getCurrentFrame()'你在代碼中不顯示'Video'的任何實例 – Esailija

+0

對你的代碼的一個評論:我建議你規定你在函數中使用的變量的作用域。它可以是私有的(通過添加'var',或者添加'this'使其在原型中可訪問)。否則,你會在全局範圍內創建大量的「垃圾」。雖然這個評論與你的問題無關。 –

回答

2

你需要調用getCurrentFrameVideo一個實例,而不是該原型本身:

var video = new Video; 
alert(video.getCurrentFrame()); 

,你可以使用原型檢索當前幀的唯一方法是使用apply()(這也需要一個實例):

var video = new Video; 
alert(Video.prototype.getCurrentFrame.apply(video)); 

編輯:它的應用程序認爲timeListener回調沒有在視頻實例的上下文中執行。您可能需要明確綁定回調到正確的範圍:

timeListener = function() 
    { 
    // ... 
     this.frame = frame; 
    // ... 
    } 

var video = new Video; 

// binding the correct context 
myPlayer.addListener('time', timeListener.bind(video)); 

timeListener關閉this現在video

+0

謝謝,我已經使用一個實例來使用函數getCurrentFrame()。也許我應該對此更精確。但我的問題是this.frame不會改變方法setUpPlayer之外。所以當我instanciate我的視頻對象,並稱之爲getCurrentFrame。該方法首先返回已經放在構造函數中的值(在我的情況下是什麼都沒有)。當我想要它返回更新的值 – Fabax