HandlebarsJS+BackboneJS通过JSON数组循环

HandlebarsJS + BackboneJS Loop through array of JSON

本文关键字:循环 数组 JSON 通过 HandlebarsJS+BackboneJS      更新时间:2023-09-26

我想显示一个按首字母排序的音乐艺术家列表。

所以我有这个主干视图:

function (App, Backbone, utils) {
    // Create a new module.
    var AllArtists = App.module();
    // Create view
    AllArtists.View = Backbone.View.extend({
        template: 'allArtistsList',
        initialize: function() {
            //this.listenTo(this.collection, 'sync', this);
        },
        afterRender: function(){
            var col1 = new Backbone.Collection();
            col1.url = App.APIO + '/i/search/artist?name=a';
            col1.fetch({success: function(){
                console.log(col1);
            }});
            this.insertView('.artistsA', new AllArtists.View({collection: col1}));
            var col2 = new Backbone.Collection();
            col2.url = App.APIO + '/i/search/artist?name=b';
            col2.fetch({success: function(){
                console.log(col2);
            }});
            this.insertView('.artistsB', new AllArtists.View({collection: col2}));          
        }
    });
    return AllArtists;
}

然后我有了我的Handlebars HTML:

<div class="artistsA">
    {{#each this}}
        <a href="{{name}}">{{name}}</a>
    {{/each}}   
</div>

到目前为止,我的JSON看起来是这样的(在本例中是字母a):

data: [ 
        {
           artist_id:78, 
           name:A Band Of Boys
         },
          {
           artist_id:79, 
           name:a Beautiful Friend
         },
         {
           artist_id:80, 
           name:A Camp
        } 
        etc. etc...

我可以看到我的console.log返回了数据,但我得到了一个空白页,所以它表明我的Handlebars有问题?我做错了什么?

基本上fetch()是异步的,它会在内部调用异步的Ajax请求。一旦获取调用成功,即在成功回调时,您必须调用insertView()。您正在观察空白页,因为您正试图在获取数据之前调用insertView()。

如果你想让它同步请求,你可以使用属性{async:false}

col1.fetch({async:false});