使用Backbone Collection构建列表

时间:2012-10-19 06:03:53

标签: javascript backbone.js

我正在尝试使用BackBone集合构建列表..出于某种原因,我无法在页面上打印它们。

js file

var DataCollection = Backbone.Collection.extend({
            model : dataModel
        });

        var dataModel = Backbone.Model.extend({
            defaults : {
                dataID : 'unknown',
                text : 'unknown',

            }
        });

        var link1 = new dataModel({ dataID: "1", text: "OMC" });
        var link2 = new dataModel({ dataID: "2", text: "Marvin Gaye" });
        var link3 = new dataModel({ dataID: "3", text: "OMC" });

        var myDataCollection = new DataCollection([ link1, link2, link3]);


   var threatData = {

                myDataCollection: myDataCollection
        };

    var compiledTemplate = Handlebars
                .compile(myTemplate);
        $('#myTable').html(
                compiledTemplate (threatData));

html文件

<ul id="Linklist">
             {{#each myDataCollection}}
                <li><a data-id="{{dataID}}" href="#">{{text}}</a></li>
             {{/each}}
        </ul>

1 个答案:

答案 0 :(得分:1)

要使模板渲染生效,您需要先将Backbone集合转换为JSON。

var threatData = {
            myDataCollection: myDataCollection.toJSON()
    };

DEMO