Backbone.js从静态JSON渲染集合视图

时间:2016-02-09 09:20:58

标签: javascript json backbone.js collections

我尝试构建一个简单的音乐库来学习Backbone.js。 Evrything工作正常,直到我尝试从JSON文件(而不是内联javascript对象)加载数据。

这是我的Javascript:

(function(){

    var myMusic = {
        Models : {},
        Collections : {},
        Views : {},
        Routers : {}
    };

    // Model
    myMusic.Models.Album = Backbone.Model.extend({
        default: {
            title : null,
            artist : null,
            cover : null,
            publicationYear : null
        },

        initialize: function(){
            console.log("Creation of the album " + this.get('title') + " from the artist " + this.get('artist'));
        }
    });

    // Collection
    myMusic.Collections.Albums = Backbone.Collection.extend({
        model : myMusic.Models.Album,
        url : "albums.json",
        initialize : function(){
            console.log("New collection created");
        }
    });

    // Collection instance
    var albumsCollection = new myMusic.Collections.Albums();
    albumsCollection.fetch();

    // Collection view
    myMusic.Views.albums = Backbone.View.extend({

        el: $("#albumsList"),

        initialize: function() {
            this.template = _.template($("#albumTemplate").html());
        },

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

    // Collection view instance
    var albumsView = new myMusic.Views.albums({ collection : albumsCollection });
    albumsView.render();

})();

HTML部分:

    <div class="albumsListWrapper">

        <script type="text/template" id="albumTemplate">
            <% _.each(albums, function(album) { %>
                <article>
                    <header>
                        <h1><%= album.title %></h1>
                        <h2><%= album.artist %></h2>
                        <h3><%= album.publicationYear %></h3>
                    </header>
                    <figure><img src="<%= album.cover %>" alt="<%= album.title %>" /></figure>
                </article>
            <% }); %>
        </script>

        <div id="albumsList" class="albumsList"></div>

    </div>

我的JSON文件:

[
    {
        "title" : "Gish",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://ecx.images-amazon.com/images/I/51sGOPMVD9L.jpg",
        "publicationYear" : 1991
    },
    {
        "title" : "Siamese dream",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://static.stereogum.com/uploads/2013/07/The-Smashing-Pumpkins-Siamese-Dream.jpg",
        "publicationYear" : 1993
    },
    {
        "title" : "Mellon Collie and the Infinite Sadness",
        "artist" : "Smashing Pumpkins",
        "cover" : "https://upload.wikimedia.org/wikipedia/fi/7/7e/Smashing_Pumpkins_-_Mellon_Collie_And_The_Infinite_Sadness.jpg",
        "publicationYear" : 1995
    },
    {
        "title" : "Adore",
        "artist" : "Smashing Pumpkins",
        "cover" : "https://s3.amazonaws.com/thisismyjam/i/6b4a1443ce6697a11537102f05b00f61.jpg",
        "publicationYear" : 1998
    },
    {
        "title" : "Machina/The Machines of God",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://yourlifeisnotyourown.files.wordpress.com/2012/02/machinathemachinesofgod.jpg",
        "publicationYear" : 2000
    },
    {
        "title" : "Machina II",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://vignette1.wikia.nocookie.net/lyricwiki/images/8/86/The_Smashing_Pumpkins-MACHINA_II_(2000).jpg",
        "publicationYear" : 2000
    },
    {
        "title" : "Zeitgeist",
        "artist" : "Smashing Pumpkins",
        "cover" : "https://s3.amazonaws.com/rapgenius/Zeitgeist.jpg",
        "publicationYear" : 2007
    },
    {
        "title" : "Oceania",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://ecx.images-amazon.com/images/I/61HWLX-iGwL.jpg",
        "publicationYear" : 2012
    },
    {
        "title" : "Monuments to an Elegy",
        "artist" : "Smashing Pumpkins",
        "cover" : "http://lecanalauditif.ca/wp-content/uploads/2015/01/Monuments_to_an_Elegy_album_cover_from_Smashing_Pumpkins.jpg",
        "publicationYear" : 2014
    }
]

问题似乎位于albumsCollection对象上。当我在console.log中时,它是空的:(

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为您的问题来自于渲染视图时尚未加载相册的事实。你可以听&#34;同步&#34;事件要避免这种情况。

string delimiter = ",";
string ss;
ss.reserve(P.n_rows * P.n_cols * P.n_slices * 20);

int max_idx = max(P.n_rows, max(P.n_cols, P.n_slices));
vector<string> idx_str(max_idx);
for(int i=0;i<max_idx;++i) idx_str[i] = std::to_string(i+1);

for (int r = 0; r < P.n_rows; r++)
{
  auto& rstr = idx_str[r];
    for (int c = 0; c < P.n_cols; c++)
    {
      auto& cstr = idx_str[c];
      string thisline = rstr + delimiter + cstr + delimiter;

        for (int s = 0; s < P.n_slices; s++)
        {
          auto& sstr = idx_str[s];
            ss += thisline
                + sstr + delimiter
                + std::to_string(data[r][c][s]) + "\n";
        }
    }
}
ofstream ofs(file, ofstream::out);
ofs.write(ss.c_str(), sizeof(char)*ss.size());
ofs.close();

您还应该避免在视图中使用对相册集的外部引用,并在myMusic.Views.albums = Backbone.View.extend({ el: $("#albumsList"), initialize: function () { this.template = _.template($("#albumTemplate") .html()); this.listenTo(this.collection,"sync",this.onSync) }, onSync:function () { this.render(); //other logic }, render: function () { this.$el.html(this.template({ albums: this.collection.toJSON() })); return this; } }); 方法中使用内部属性this.collection而不是albumsCollection