【问题标题】:Backbone + Handlebars: template not getting the dataBackbone + Handlebars:模板未获取数据
【发布时间】:2014-06-01 01:11:28
【问题描述】:

我正在将数据从我的主干视图发送到把手模板(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>

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

【问题讨论】:

  • 好点! jsfiddle.net/8NhjD
  • 您真的将模板存储在&lt;div&gt; 中吗?
  • @muistooshort - 是的,这不是一个好习惯吗?
  • 模板很少是有效的 HTML(它们只是看起来像 HTML 的文本),因此您应该将它们存储在 &lt;script type="text/x-handlebars"&gt; 容器中,以免浏览器对其进行干预。
  • 哇,很高兴知道。谢谢@muistooshort!

标签: backbone.js handlebars.js


【解决方案1】:

将集合获取从视图的初始化方法移动到路由处理程序解决了这个问题。

【讨论】:

    【解决方案2】:

    您的问题是您正在传递模型,这些模型不直接公开它们的属性。试试这样的:

    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();
    

    【讨论】:

    • 我用更详尽的例子更新了我的答案
    猜你喜欢
    • 2014-03-11
    • 2012-09-08
    • 2014-06-05
    • 2013-12-26
    • 2012-04-10
    • 1970-01-01
    • 2023-03-27
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多