1

I have template in html as:

 <script type="text/template" id="table-template">
     <div id="table-body"></div>                        
 </script>

My backbone view look like this:

var app = app || {};
$(function ($) {
    'use strict';
    info = [
        {
            "id": 1,
            "Age": 70,
            "salary": 700000,
            "name": "Mike",
        },
        {
            "id": 2,
            "Age": 18,
            "salary": 30000,
            "name": "Mike",
        },
    ];
    app.infoView = Backbone.View.extend({
        initialize: function () {
            console.log('initialize');
        },
        drawinfoTable: function () {
            console.log('create datatable');
            $('#test').dataTable({
                "aaData": groupdata,
                "aoColumns": [
                    { "mDataProp": "id" },
                    { "mDataProp": "age" },
                    { "mDataProp": "sal" },
                    { "mDataProp": "active" },
                    { "mDataProp": "name" }
                ]
            });
        }
        render: function () {
            console.log('render');
            var template = _.template($("#-template").html(), {});
            this.$el.html(template);
        }
    });
});

Actually with above JSON data, I want to create datatable with column name id, sal, active & sal. I am using jquery.dataTables.min.js to create datatable. Then, I want to insert that datatable inside "table-body" div, which is present inside "table-template". Your help will be greatly appreciated.

4

2 回答 2

2

您的模板应类似于:

<script type="text/template" id="table-template">
     <div id="table-body">
         <table>
             <tr>
                 <th>id</th>
                 <th>age</th>
                 <th>salary</th>
                 <th>name</th>
             </tr>
             <% _.each(info, function(data, index) { %>
             <tr>
                  <td><%= data.id %></td>
                  <td><%= data.Age %></td>
                  <td><%= data.salary %></td>
                  <td><%= data.name %></td>
             </tr>
             <% }); %>
         </table>
     </div>                        
</script>

和渲染方法:

render: function () {
    console.log('render');
    var template = _.template($("#-template").html(), { info : info });
    this.$el.html(template);
}
于 2013-03-15T08:25:46.770 回答
1

@Sylvanus 已经回答了如何渲染视图。您只需要激活数据表。

尝试对他的渲染函数进行以下修改

render: function () {
    console.log('render');
    var template = _.template($("#-template").html(), { info : info });
    this.$el.html(template);
    //initialize datatable
    this.$el.find('#table-body').find('table').dataTable();
}

您只需要在模板渲染完成后初始化数据表。

于 2013-03-15T08:36:59.470 回答