2011-11-23 61 views
1
User = Backbone.Model.extend({ 
    urlRoot: "users", 

    initialize: function(){ 
    this.fetch(); 
    } 
}); 

    var HomeView = Backbone.View.extend({ 
    el: '#container', 
    template: _.template($("#home-template").html(), this.model), 

    render: function() { 
     $(this.el).html(this.template); 
     return this; 
    } 
    }); 

    var App = Backbone.Router.extend({ 
     routes: { 

      '/home':  'home', 
     }, 

     home: function() { 
     var user = new User({id: 1}); 
     homeView = new HomeView({ 
      model: user 
     }); 
     this.homeView.render(); 
     } 
    }); 

由於某種原因,我無法將模型數據注入到HomeView模板中。我看到ajax請求被髮送並返回的數據是正確的。我在調用視圖時將靜態數據放在同一個地方,它工作正常。Backbone.js - 獲取json數據到視圖

有什麼建議嗎?

回答

3

我認爲這是因爲你在錯誤的時間執行你的模板。應該在render被調用時完成,如下所示:

var HomeView = Backbone.View.extend({ 
    el: '#container', 
    template: _.template($("#home-template").html()), 

    render: function() { 
    $(this.el).html(this.template(this.model.toJSON())); 
    return this; 
    } 
}); 
+0

就是這樣。謝謝! – user577808