简体   繁体   English

如何使用backbone.js中的额外值在视图中呈现集合

[英]How to render collection in the view with extra values in backbone.js

I would like to know how should I pass some values with collection which is not part of any modele? 我想知道我应该如何传递一些不属于任何模型的集合的值? For example in this example http://jsfiddle.net/5ZaFa/20/ I assigned the title of the view and passed whole collection to the template, and inside that template loop every model of that collection. 例如,在这个示例http://jsfiddle.net/5ZaFa/20/中,我分配了视图的标题并将整个集合传递给模板,并在该模板内部循环该集合的每个模型。

  1. Is it possible to not write long variables like items.models[x].attributes.id , it would be good if i could do something like this items[x][id] 是否有可能不写像items.models[x].attributes.id这样的长变量,如果我可以做这样的事情items[x][id]会很好
  2. I know it would be possible to create separate views for every row and title. 我知道可以为每一行和标题创建单独的视图。 But I would like to keep it in one view. 但我想将其保留在一个视图中。 Could you suggest me please? 你能建议我吗? May be there any way to do this? 可能有任何办法吗?

If something is not clear I will try to provide more information. 如果不清楚,我会尝试提供更多信息。

Thanks, 谢谢,

Instead of passing in items.toJSON() pass in an object with the names you wish to use, then use the names to reference the values you wish to reference in your template. 而不是传入items.toJSON()传递具有您要使用的名称的对象,而是使用名称来引用您希望在模板中引用的值。

Your render function will then look like this: 您的渲染功能将如下所示:

render: function() {
            template= _.template($('#list_template').html());
            $(this.el).html(template({
                items : this.collection.toJSON(),
                title : "Title of the listing"
            }));
            $('#list_container').html(this.el);
        }

and change your template to look like this: 并将模板更改为如下所示:

<% for(x in items) { %>
   <li><%= items[x].id %> - <%= items[x].name %></li>
<% } %>

Here's a link to your modified jsFiddle 这是您修改后的jsFiddle的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM