2014-05-07 46 views
0

我有兩個JavaScript「類」。其中一個應該是一個普通的類,它會實例化另一個子類。在另一個內部訪問一個JavaScript類

不知怎的,這將引發一個undefined is not a function錯誤:

this.progress = new Uploader.Progress({ 
     matcher: options.matcher, 
    }); 

我使用下劃線作爲包括通過rails資產管道的依賴需要聲明。下面是完整的代碼:

//= require underscore 

if (typeof Uploader === "undefined") { 
    var Uploader = {}; 
} 

(function() { 
    var Progress = Uploader.Progress = function(options) { 
    options || (options = {}); 

    if(options.matcher) this.$matcher = $(options.matcher); 

    this.initialize.apply(this, arguments); 
    }; 

    _.extend(Progress.prototype, {}, { 
    initialize: function() { 
     this.listen(); 
    }, 

    listen: function() { 
     this.$matcher.on("fileuploadprogress", function(e, data) { 
     var progress = parseInt(data.loaded/data.total * 100, 10); 
     data.context.find(".upload-progress").css({ "width": progress + "%" }); 
     }); 

     return this; 
    }, 
    }); 
})(); 

(function() { 
    var Uploader = Project.Uploader = function(options) { 
    options || (options = {}); 

    if(options.url) this.url = options.url; 
    if(options.matcher) this.$matcher = $(options.matcher); 

    this.progress = new Uploader.Progress({ 
     matcher: options.matcher, 
    }); 

    this.initialize.apply(this, arguments); 
    }; 

    _.extend(Uploader.prototype, {}, { 
    initialize: function() { 
     this.listen(); 
    }, 

    listen: function() { 
     var _this = this; 

     this.$matcher.fileupload({ 
     url: this.url, 
     type: "POST", 
     dataType: "json", 

     add: function(e, data) { 
      data.context = _this.$matcher.closest("form"); 
      data.submit() 
      .success(function(result, textStatus, jqXHR) { 
       console.log("submitted"); 
      }); 
     }, 
     }); 

     return this; 
    }, 
    }); 
})(); 

var uploader = new Project.Uploader({ 
    matcher: "#video_file", 
    url: "https://stackoverflow.com/users/1/videos", 
}); 
+0

JavaScript錯誤來源於哪個行號?我們可以看到需要使用underscore.js的代碼嗎? –

+0

格雷格,第39行導致錯誤('this.progress = new Uploader.Progress({...'),第1行需要underscore.js。 – Adam

+0

好的,我懷疑問題在於那個花哨的命名空間在'var Uploader = Project.Uploader = function(...)'中。 – Adam

回答

1

當你說

this.progress = new Uploader.Progress({ 
     matcher: options.matcher, 
    }); 

它相匹配的Uploader defined in the功能scope`這是

var Uploader = Project.Uploader = function(options) { 

,這一次沒有屬性Progress所以Uploader.Progressundefined。因此,錯誤。

爲了解決這個問題,改變

var Uploader = Project.Uploader = function(options) { 

var SomeOtherVariable = Project.Uploader = function(options) { 

所以現在當你調用new Uploader.Progress({它將啓動功能範圍之外尋找Uploader,因爲它不會在功能範圍內找到它。將調用在全局範圍內爲Uploader.Progress設置的正確功能。

1

ü創建模塊範圍

if (typeof Uploader === "undefined") { 
var Uploader = {}; 
} 

一個上傳對象,但然後ü創建另一個地方一個

var Uploader = Project.Uploader = function(options) ... 

在當地的約束力*這樣的東西對象在全局對象中不可見。那是一種很奇怪的風格。