2012-10-30 50 views
0

我是backbone.js世界的新手。我想用Backbone.js的與服務器進行通信,並呈現在桌子上。我是從服務器上使用下面的代碼獲取數據的員工詳細信息:從數據庫獲取數據並將其呈現在backbone.js的表格中

var EmployeeCollection = Backbone.Collection.extend({ 
    model: Person, 
    url:"http://localhost:4000/get/employee", 
    parse : function(res) 
    { 
     console.log('response inside parse' + res); 
     return res; 
    } 

}); 

var employee = new EmployeeCollection(); 
employee.fetch(); 

在日誌語句我得到:response inside parse[object Object],[object Object],[object Object]

但我不知道接下來會發生什麼。如何從我得到的對象中檢索數據並將其呈現在表格中。有人有建議嗎?

回答

4

讓我們假設您的HTML頁面中有一個表格,其中id="employee"已被定義爲template,對應於表格中的一行。爲簡單起見,我們asssume員工行只是有firstnamelastname

<table id="employee"> 
    <thead> 
    <tr><td>Firstname</td><td>Lastname</td></tr> 
    </thead> 
    <tbody> 
    </tbody> 
</table> 
<script type="text/template" id="employee-template"> 
    <td><%= firstname %></td><td><%= lastname %></td> 
</script>​ 

需要兩個views一個渲染表,以及一個呈現在表的每一行。它們可能如下所示:

//a (table) view to render the list of employees 
var employee_list_view = Backbone.View.extend({ 
    el: $('#employee'), 
    initialize: function() { 
     this.collection.bind("add", this.render, this); 
    }, 

    //this creates new rows in the table for each model in the collection 
    render: function() { 
     _.each(this.collection.models, function(data) { 
      this.$el.append(new employee_view({ 
       model: data 
      }).render().el); 
     }, this); 
     return this; 
    } 
}); 

//a (row) view to render each employee 
var employee_view = Backbone.View.extend({ 
    tagName: "tr", 
    template: _.template($("#employee-template").html()), 

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

從服務器獲取集合後,項目將存儲在集合中。您可以使用以下代碼查看檢索到的數據。成功時,我們創建一個新的員工列表(本例中爲表)並傳遞員工集合。

var employee = new EmployeeCollection(); 

employee.fetch({ 
    success: function() { 
     console.log(employee.toJSON()); 
     new employee_list_view({collection: employee}).render(); 
    }, 
    error: function() { 
     console.log('Failed to fetch!'); 
    } 
}); 

注意:建議使用成功/失敗回調。

看看這個working version on JSFiddle

+0

'_.each(this.collection.models,...'可能是因爲['this.collection.each(...)'(HTTP更好:/ /backbonejs.org/#Collection-Underscore-Methods)。你不想'this。$('tbody')。append(...)'添加'employee_view's嗎? –

+0

感謝您的評論!猜,我正在學習很多參與Q/A的東西。乾杯:) –

0

首先,如果您以這種方式使用console.logconsole.log('response inside parse', res);,您可以獲得更多信息。 res將不會轉換爲字符串,但它將顯示爲具有其所有屬性和值的JavaScript對象。然後,檢查backbone.js文檔Collection.parse並閱讀res在此上下文中的內容以及此方法應返回的內容。

可能下一步將是創建一個視圖,該視圖使用您的集合中的某些模板和數據呈現表格。

相關問題