BackboneJS - 使用Handlebars.js调用多个集合

时间:2013-12-16 10:05:52

标签: javascript backbone.js handlebars.js

如何使用Handlebars.js获取和显示多个骨干集合?我创建了4个json文件,每个文件都分配给自己的集合和模型。

在我的路由器中,我有初始化:

initialize: function () {
   this.allcategoryMenuCollection = new AllCategoryMenuCollection();
   this.natcategoryMenuCollection = new NatCategoryMenuCollection();
   this.intcategoryMenuCollection = new IntCategoryMenuCollection();
   this.topcategoryMenuCollection = new TopCategoryMenuCollection();
}

然后我在路线中定义,当您点击特定链接时,您将被重定向到某个页面:

newpage: function () {

this.artistpageLeftMenuView = new ArtistpageLeftMenuView({el:'#leftMenu'});
this.artistpageLeftMenuView.collections = {
    allcategoryMenuCollection: this.allcategoryMenuCollection,
    natcategoryMenuCollection: this.natcategoryMenuCollection,
    intcategoryMenuCollection: this.intcategoryMenuCollection,
    topcategoryMenuCollection: this.topcategoryMenuCollection
};
this.artistpageLeftMenuView.render();
}

我的HTML文件是:

<ul class="sbm2">
    {{categoryAll}}
    {{#each .}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

<ul class="sbm2">
    {{categoryNat}}
    {{#each .}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

<ul class="sbm2">
    {{categoryAll}}
    {{#each .}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

<ul class="sbm2">
    {{top100}}
    {{#each .}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

在我的Backbone View中我有:

render: function() {
  $(this.el).html(this.template({categoryAll:this.collections.allcategoryMenuCollection.toJSON()}));
  $(this.el).append(this.template({top100:this.collections.topcategoryMenuCollection.toJSON()}));
  $(this.el).append(this.template({categoryNat:this.collections.natcategoryMenuCollection.toJSON()}));
  $(this.el).append(this.template({categoryInt:this.collections.intcategoryMenuCollection.toJSON()}));
  return this;
}

我不知道它是什么,但是它向我展示了html模板4次,没有任何内容?!?!

1 个答案:

答案 0 :(得分:0)

我不确定我明白你要做什么。因为我的解决方案很简单。 我会像这样制作模板:

<ul class="sbm2">
  {{#each allcategoryMenuCollection}}
    <li> 
      <a href="{{this.url}}">{{this.name}}</a>
    </li>
  {{/each}}
</ul>
    <ul class="sbm2">
    {{#each natcategoryMenuCollection}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

<ul class="sbm2">
    {{#each intcategoryMenuCollection}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

<ul class="sbm2">
    {{#each topcategoryMenuCollection}}
    <li> 
        <a href="{{this.url}}">{{this.name}}</a>
    </li>
    {{/each}}
</ul>

用以下方式渲染:

render: function() {
  $(this.el).html(this.template(this.collections.toJSON()));
  return this;
}