【问题标题】:Looping an array in a model with Backbone and handlebars使用 Backbone 和车把在模型中循环数组
【发布时间】:2013-11-17 22:21:37
【问题描述】:

我正在为我所在城市的公交时刻表开发一个带有主干和把手的应用程序。一站式的型号是:

    define(["jquery", "underscore", "backbone"],
      function ($, _, Backbone){

    var stop = Backbone.Model.extend({
        defaults : {
            id : "23",
            lon : "43,465187",
            lat : "-80,522372",
            listabus : ["80", "83", "106"]

        }

    });

    return stop;

});

其中“Listabus”是经过 23 号站附近的所有公共汽车的列表。我不知道如何在模板中循环数组...帮帮我! :D 感谢您的建议

【问题讨论】:

  • 你使用的模板引擎是什么?
  • 你读过handlebars documentation吗?
  • 我正在使用 underscore.js!我看过文档,但没有回答我的问题。
  • this answer 可能会帮助你

标签: javascript backbone.js


【解决方案1】:

这是你的 html:

<!-- below is your template !-->
<script id="bus-stops" type="text/x-handlebars-template">
<ul>
    {{#each stops}}
    <li>{{this}}</li>
    {{/each}}
</ul>
</script>

<!-- result container !-->
<div id="result"></div>

还有js代码

   var BusStop = Backbone.Model.extend(),
       busStop = new BusStop({stops: ['a', 'b', 'c']});
       template = $('#bus-stops').html(),
       compiler = Handlebars.compile(template),
       html = compiler({stops: busStop.get('stops')});

   $('#result').html(html);

抱歉,jsfiddle 不适用于车把

【讨论】:

    【解决方案2】:

    您只需将模型属性作为对象传递给下划线模板函数。第一个参数是模板,第二个参数是您的数据。您可以传入任何对象数据,但由于显而易见的原因,下划线与 model.toJSON() 配合得非常好。

    this.$('#insertWherever').html(_.template($('#busList'), stopModel.toJSON()));
    

    你的模板看起来像这样。

    <script id="busList" type="text/html">
    <ul>
    
      <% _.each(listabus, function(busNumber){ %>
    
        <li><%= busNumber %></li>
    
      <% }); %>
    
    </ul>
    </script>
    

    总而言之,&lt;% %&gt; 是一种逃避和运行任意 JS 代码的方法。 &lt;%= %&gt; 是一种将内容插入或输出到模板中的方法。

    http://underscorejs.org/#templatehttp://underscorejs.org/#each

    如果你使用 require.js,你可以下载一个名为 text 的插件!

    这允许您在依赖项中定义 HTML 文件,并使您的模板驻留在它们自己的单独文件中。这与上述使用嵌入脚本标签和 jquery 从您正在使用的任何视图中获取模板的方法相反。

    见插件/文字@http://requirejs.org/docs/download.html

    【讨论】:

    • 非常非常好!其实我用require,所以你回答了我想问的问题!非常感谢,它工作得很好:D
    • 酷。如果它解决了问题,请不要忘记检查正确答案。 ;)
    猜你喜欢
    • 2019-08-15
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 2021-02-19
    • 2014-04-16
    • 2015-06-03
    • 2022-08-15
    • 1970-01-01
    相关资源
    最近更新 更多