2014-02-09 21 views
3

下面是爲了從收集獲取正確的數據初始化時,應接收模塊的名字來查看我的初始化函數。listenTo上收集復位收集後不被調用是獲取

的問題是:後收集獲取

  1. Listento不重定向到render()方法,還它給我的控制檯

TypeError: e is undefined

上的錯誤我用下面的代碼犯了什麼錯誤?

initialize: function() {   

    var that = this; 
     if(this.options.module === 'questions'){     

      require([ 
       'app/collections/questions' 
      ], function(QuestionsCollection){     
       var moduleCollection = new QuestionsCollection(); 
       that.collection = moduleCollection; 
       moduleCollection.fetch({ 
        reset: true, 
        success: function(){}, 
        error: function(){} 
        });                   
      });     

     } 

     this.listenTo(this.collection, 'reset', this.render); 
     this.listenTo(Backbone, 'close:Home', this.close); 
    }, 

回答

1

您的問題是riquire.js,當你寫require([/*jsFile*/], callback);的加載後調用callback是異步的。因此,當您立即致電require([...後,您會致電this.listenTo(this.collection, 'reset', this.render);,並且在執行最後一行時,尚未加載,callback尚未調用,因此this.collection未定義。

看一看這個例子http://jsfiddle.net/ZZuGC/1/,並且命令console.log('require'); & console.log('listenTo');被打印到控制檯。


我認爲,要解決你的問題如下:

initialize: function() {   

var that = this; 
    if(this.options.module === 'questions'){     

     require([ 
      'app/collections/questions' 
     ], function(QuestionsCollection){     
      var moduleCollection = new QuestionsCollection(); 

      that.collection = moduleCollection; 
      // here is my suggestion 
      that.listenTo(that.collection, 'reset', that.render); 

      moduleCollection.fetch({ 
       reset: true, 
       success: function(){}, 
       error: function(){} 
       });                   
     });     

    } 
    this.listenTo(Backbone, 'close:Home', this.close); 
}, 

我已經更新的例子http://jsfiddle.net/ZZuGC/2/

+0

我相信你分析的問題,但你建議如何在這種情況下做的,我用這個解決方案,以減少僅由從服務器請求加載的文件的數量。 – ahmedsaber111

4

我相信這是一個範圍問題,其中require模塊在關閉。請嘗試以下操作:

initialize: function() {   

var that = this; 
    if(this.options.module === 'questions'){     

     require([ 
      'app/collections/questions' 
     ], function(QuestionsCollection){     
      var moduleCollection = new QuestionsCollection(); 
      moduleCollection.fetch({ 
       reset: true, 
       success: function(){}, 
       error: function(){} 
       }); 
      that.listenTo(moduleCollection, 'reset', that.render);              
     });     
    } 

    this.listenTo(Backbone, 'close:Home', this.close); 
}, 
+0

非常感謝,我想,這可能是範圍問題,做了很多解決方案,包括剛剛提到的解決方案,但似乎並非問題,認爲Rida的答案更接近解決問題,你呢? – ahmedsaber111