2013-02-04 129 views
2

我覺得我錯過了一些非常明顯的東西。這裏是我的模型:骨幹模型:返回空模型

define([ 
    'underscore', 
    'backbone' 
], function(_, Backbone) { 
    var spamTermsModel = Backbone.Model.extend({}); 

    return spamTermsModel; 
}); 

下面是一個使用模型中的集合:

define([ 
     'jquery', 
     'underscore', 
     'backbone', 
     'models/spamTermsModel' 
    ], 
    function($, _, Backbone, spamTermsModel) { 
     var spamTermsCollection = Backbone.Collection.extend({ 
      model: spamTermsModel, 
      url: 'spam-terms', 
      initialize: function(models, options) { 
       //console.log(models); 
       this.fetch({ 
        success: function(data, options) { 
         //console.log(data); // logs data correctly 
        } 
       }); 
      } 
     }); 

     return spamTermsCollection; 
    } 
); 

這裏就是我所說的集合的觀點:

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'models/spamTermsModel', 
    'collections/spamTermsCollection' 
], function($, _, Backbone, spamTermsModel, spamTermsCollection) { 
    var searchTermsView = Backbone.View.extend({ 
     initialize: function() { 
      var stm = new spamTermsModel(); 
      console.log(stm); // returns function() 
      this.collection = new spamTermsCollection(); 
      console.log(this.collection.toJSON()); // returns empty collection 
     }, 
     retrieveTemplate: function(model) { 
      return _.template($('#spamTermsTemplate').html(), model); 
     }, 
     createList: function() { 
      var list = ''; 
      _.each(this.collection.toJSON(), function (obj) { 
       list += obj.term + ', '; 
       //console.log(obj); 
      }); 
      //console.log(this.collection.toJSON()); 
      return list; 
     }, 
     render: function() { 
      list = this.createList(); 
      this.$el.html(this.retrieveTemplate(list)); 
      return this; 
     } 
    }); 

    return searchTermsView; 


    }); 
}); 

最後我的路線:

router.on('route:updateSpamTerms', function() { 
    require(['views/spamTermsView'], function(st) { 
      s = new st(); 
      $('#web-leads').html(s.render().el); 
    }); 

}); 

我認爲p因爲它是console.log()的函數()。我覺得它應該記錄一個新的模型。我試圖返回一個新的模型,但我得到一個錯誤,該模型不是一個構造函數。我在這裏錯過了什麼?

回答

2

this.collection = new spamTermsCollection(); console.log(this.collection.toJSON()); // returns empty collection

這是因爲你的抓取是異步的,您要訪問它之前,它是成功抓取。

您可以綁定到集合的reset事件,然後呈現您的集合視圖。

this.collection.on('reset', this.render, this);

這應該工作,如果取總是同步的,但如果由於某種原因,它是不是在未來,你可能有問題。你可以考慮移出initialize以確保:

this.collection = new spamTermsCollection(); 
this.collection.on('reset', this.render, this); 
this.collection.fetch(); 
+0

我知道這是明顯的東西。謝謝,保羅。 – sehummel