2015-10-11 20 views
1

我剛剛開始學習模塊化設計原則,並且我相信我不瞭解我的一種方法的上下文。在控制檯中,我得到Uncaught TypeError: Cannot read property 'val' of undefined - line 19。如果有問題,我正在使用Firebase。JS模塊化設計 - 上下文問題

這裏是我的代碼:

(function(){ 
    var UpdateTable = { 
     resources: Resources, 
     init: function(){ 
      this.cacheDom(); 
      this.render(); 
      this.update(snapshot); // Changed this line /// 
     }, 
     render: function(){ 
      this.resources.on('value', this.update); 
     }, 
     cacheDom: function(){ 
      this.$table = $('#resourceTable'); 
     }, 
     update: function(snapshot){ 
      console.log(snapshot.val()); 
      for(var resource in this.resources){ 
       this.$table.append('<tr><td>' + this.resources[resource].name + '</td><td>' + this.resources[resource].language + '</td></tr>'); 
      } 
     } 
    }; 
    UpdateTable.init(); 
})(); 
+2

當您從init方法調用更新時,不會傳遞任何東西作爲快照參數。 –

回答

1

如果你想使這個真正模塊化,我建議通過snapshot爲你的模塊的參數。這將解決您的問題。

(function(snapshot){ // <----- Here I receive snapshot from the invoker 
    var UpdateTable = { 
     resources: Resources, 
     init: function(){ 
      this.cacheDom(); 
      this.render(); 
      this.update(snapshot); // Changed this line /// 
     }, 
     render: function(){ 
      this.resources.on('value', this.update); 
     }, 
     cacheDom: function(){ 
      this.$table = $('#resourceTable'); 
     }, 
     update: function(snapshot){ 
      console.log(snapshot.val()); 
      for(var resource in this.resources){ 
       this.$table.append('<tr><td>' + this.resources[resource].name + '</td><td>' + this.resources[resource].language + '</td></tr>'); 
      } 
     } 
    }; 
    UpdateTable.init(); 
})(snapshot); // <---- Here I am passing snapshot from global context to the module context 
+0

我很抱歉無法理解這一點,但我使用了確切的代碼,並且在最後一行中顯示錯誤:'Uncaught ReferenceError:snapshot is not defined' 。我在這裏做了一個Codepen: http://codepen.io/dcain19/pen/MaveqE – dericcain

+0

所以這意味着你實際上需要在全局上下文中提供'''snapshot'''。 –

+0

只是爲了說明,請在模塊前添加: var snapshot = $(document); –

0

您指定的更新應該採取一個參數 - shapshot - 但不是通過它的init()。當你給一個函數一個參數時,它是一個隱式變量聲明。

var args = 1; 
function f(args) { 
    console.log(args); 
} 

f(); 
// => 'undefined' 

相反,你想:

var args = 1; 
function f() { 
    console.log(args); // args now looks to the outer scope 
} 

f(); 
// => 1 

或者

var args = 1; 
function f(args) { 
    console.log(args); 
} 

f(args); // args is explicitly passed in 
// => 1 
+0

@JonahWillams我更新了我的問題中的代碼,但現在我得到了'Uncaught ReferenceError:snapshot is not defined'。我不太明白我出錯的地方。 – dericcain

+0

快照在哪裏?您的錯誤是由於快照不適用於任何父級作用域 –