在具有主干和车把的模型中循环数组

Looping an array in a model with Backbone and handlebars

本文关键字:模型 循环 数组      更新时间:2023-09-26

我正在为我所在城市的巴士时刻表开发一个带有骨干和车把的应用程序。一站式的模式是:

    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感谢建议

这是

你的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 不适用于车把

您只需要将模型属性作为对象传递到下划线模板函数中。第一个参数是模板,第二个参数是您的数据。您可以传入任何对象数据,但出于显而易见的原因,下划线在 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>

总而言之,<% %>是一种转义和运行任意 JS 代码的方法。<%= %>是一种将内容插入或输出到模板中的方法。

请参阅 http://underscorejs.org/#template 和 http://underscorejs.org/#each

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

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

查看插件/文本@http://requirejs.org/docs/download.html