Backbone + Handlebars:模板无法获取数据

时间:2014-04-16 23:01:44

标签: backbone.js handlebars.js

我将数据从我的主干视图发送到车把模板(js fiddle:http://jsfiddle.net/8NhjD/),如下所示:

this.$el.html(this.template({
        users: that.users.toJSON(),
        audiences: that.audiences.toJSON()
}));

我试图访问这样的用户和受众列表:

<select name="user" class = "form-control">
{{#each users}}
    <option value="{{name}}">{{name}}</option>
{{/each}}
</select>

但是,用户和受众的下拉菜单都是空的。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

您的问题是您传递的模型不直接公开其属性。尝试这样的事情:

this.$el.html(this.template({
        users: that.users.toJSON(),
        audiences: that.audiences.toJSON()
}));

<强>已更新

没有完整的小提琴,很难看出你哪里出错了。这是一个工作小提琴:http://jsfiddle.net/moderndegree/qW7Tz/

HTML:

<script id="thing-template" type="text/x-handlebars-template">
<ul>
    {{#each things}}
    <li>{{this.thing}}</li>
    {{/each}}
</ul>
</script>
<div id="thing-view"></div>

JS:

var ThingModel = Backbone.Model.extend({}),
    ThingCollection = Backbone.Collection.extend({
        model: ThingModel
    }),
    ThingView = Backbone.View.extend({
        el: '#thing-view',
        template: Handlebars.compile($("#thing-template").html()),
        initialize: function(){
            this.things = new ThingCollection([{thing: 'purple'}, {thing: 'monkey'}, {thing: 'dishwasher'}]);
        },
        render: function(){
            console.log(this.things.toJSON());
            this.$el.html(this.template({
                things: this.things.toJSON()
            }));
            return this;
        }
    });
var view = new ThingView().render();

答案 1 :(得分:0)

将视图的初始化方法中的集合提取移动到路由处理程序解决了该问题。