从数据库获取数据并将其呈现到backbone.js中的表

时间:2012-10-30 11:13:32

标签: javascript json 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]

但我不知道接下来会发生什么。如何从我得到的对象中检索数据并将其呈现到表中。有人有建议吗?

2 个答案:

答案 0 :(得分:4)

我们假设您的HTML页面中有一个表id="employee",并且您已经定义了与表中一行对应的template。为简单起见,我们假设员工行只有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

答案 1 :(得分:0)

首先,如果您以这种方式console.log使用console.log('response inside parse', res);,则可以获得更多信息。 res不会转换为字符串,但会显示为包含其所有属性和值的JavaScript对象。然后,检查backbone.js文档Collection.parse并阅读res在此上下文中的内容以及此方法应返回的内容。

可能下一步是创建一个View,它使用你的集合中的一些模板和数据呈现一个表。