2011-09-07 62 views
2

我試圖顯示使用backbone.js的項目列表。 基本上,骨幹應該能夠將項目提取到Projects集合中。 這可以工作,正如我從異步請求中可以看出的那樣充滿了項目。無法預裝服務器使用Backbone.js和Tastypie收集

但是,如何在頁面加載時呈現它們?沒有太多關於使用reset()方法來引導模型的文檔。任何幫助表示讚賞!謝謝。

app.js:

var oldSync = Backbone.sync; 

Backbone.sync = function(method, model, success, error){ 
    var newSuccess = function(resp, status, xhr){ 
     if(xhr.statusText === "CREATED"){ 
      var location = xhr.getResponseHeader('Location'); 
      return $.ajax({ 
         url: location, 
         success: success 
        }); 
     } 
     return success(resp); 
    }; 
    return oldSync(method, model, newSuccess, error); 
}; 

(function($) { 
    window.Project = Backbone.Model.extend({}); 

    window.Projects = Backbone.Collection.extend({ 
     model: Project, 
     url: PROJECT_ENDPOINT, 
     parse: function(data) { 
      return data.objects; 
     } 
    });  

    window.ProjectView = Backbone.View.extend({ 
     tagName: 'li' , 
     className: 'project', 



     initialize: function() { 
      _.bindAll(this, 'render'); 
      this.model.bind('change', this.render); 

      this.projects = new Projects(); 
      this.projects.fetch(function(data) { 
       console.log("haha"); 
      }); 

      this.template = _.template($('#project-template').html()); 
     }, 
     render: function() { 
      var renderedContent = this.template(this.model.toJSON()); 
      $(this.el).html(renderedContent); 
      return this; 
     } 
    }); 

})(jQuery); 

模板:

......... 
    <script> 
     PROJECT_ENDPOINT = "{% url api_dispatch_list resource_name="project" %}";   
    </script> 


    <script type="text/template" charset="utf-8" id="project-template"> 
     <span class="project-title"><%= title %></span> 
    </script> 

    </head> 

    <body> 
     <div id="container"></div> 
    </body> 
</html> 

回答

3

您可以添加自舉模式的模板:

<script> 
    PROJECT_ENDPOINT = "{% url api_dispatch_list resource_name="project" %}"; 
    INITIAL_DATA = <%= collection.to_json %> 
</script> 

然後在你的視圖構造函數中用this.projects.reset(INITIAL_DATA)替換this.projects.fetch(...)

+0

是的,這工作,給了我新的見解。謝謝! – Gijs

3

我想建立我的應用程序有某種「開始」功能,我用JSON數據要求的預載項目。

function MyApp(){ 
    this.start = function(initialModels){ 
    var myModels = new MyCollection(initialModels); 
    var modelsView = new MyModelsView({collection: myModels}); 
    modelsView.render(); 
    // ... other startup code here 
    } 
} 

和HTML頁面有一個腳本博客,看起來是這樣的:

<script language="javascript"> 
    var myApp = new MyApp(); 
    myApp.start(<%= mymodel.to_json %>) 
</script> 

希望幫助