2013-04-10 150 views
1

嗨我正在尋找適當的解決方案來將JSON加載到Backbone集合。我看到很多帖子都出現這個問題,但我仍然不明白如何正確地做到這一點。 例如,您能解釋一下爲什麼這個項目不起作用嗎? http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/將JSON文件加載到Backbone集合

編輯:
當我看到使用Firebug的結果,它顯示我一個空的對象,集合爲空。 爲什麼?
編輯:
嗯,仍然無法正常工作:/現在我沒有看到任何東西在螢火蟲和一頁。 :(

 $(function() { 
      var Profile = Backbone.Model.extend(); 

      var ProfileList = Backbone.Collection.extend({ 
       model: Profile, 
       url: 'profiles.json' 
      }); 

      var ProfileView = Backbone.View.extend({ 
       el: "#profiles", 
       template: _.template($('#profileTemplate').html()), 
       render: function(eventName) { 
        _.each(this.model.models, function(profile){ 
         var profileTemplate = this.template(profile.toJSON()); 
         $(this.el).append(profileTemplate); 
        }, this); 

        return this; 
       } 
      }); 

      var profiles = new ProfileList();  
      var profilesView = new ProfileView({model: profiles}); 
      var profiles = new ProfileList(); 
      profiles.fetch(); 
      profiles.bind('reset', function() { 
       console.log(profiles); 
       profilesView.render(); 
      }); 

     }); 
+1

「*你能解釋我爲什麼請本項目不工作?*」什麼部分不工作? – Loamhoof 2013-04-10 13:06:17

+0

當我看到使用Firebug的結果,它顯示我是一個空的對象,集合是空的,爲什麼? – Agata 2013-04-10 13:11:06

+0

但是教程的哪一部分?你執行了哪些代碼? – Loamhoof 2013-04-10 13:15:42

回答

3

你獲取調用是異步的,因爲我敢肯定,這是寫在教程所以,當你在做的console.log,您的收集仍然是空的
教程更遠..。。:

var profiles = new ProfileList(); 
profiles.fetch({reset: true}); 
profiles.bind('reset', function() { console.log(profiles); }); 

這應該工作。