当用户转到 时http://example.com/#/playlist
,我想列出一些歌曲。
http://example.com
当您第一次访问并单击链接时,它会起作用(列出所有歌曲)<a href="#/playlist">Playlist</a>
。
但是,如果您直接转到http://example.com/#/playlist
,则不会显示任何内容。
当我记录 this.collection 属性时,集合总是相同的(如果你使用链接,或者直接访问)。
唯一不同的是,this.collection.each( function ( song ) {} );
在下面的 render-function 中,直接访问 URL 时不会循环。
这是代码:
define(
[
'jQuery',
'Underscore',
'Backbone',
'collections/songlist',
'views/song'
],
function ($, _, Backbone, SonglistCollection, SongView)
{
var PlaylistView = Backbone.View.extend({
// properties
el: '#content',
tagName: 'ul',
collection: new SonglistCollection(),
/**
* Initialize
*/
initialize: function()
{
// load songs
this.collection.bind( 'reset', this.render(), this );
this.collection.fetch();
},
/**
* Render
*/
render: function ()
{
this.$el.html('');
console.log(this.collection);
this.collection.each( function ( song )
{
var songItem = new SongView( { model: song } );
this.$el.append( songItem.el );
}, this);
}
});
return new PlaylistView;
}
);
问题出现在这里,在“每个循环”中:
render: function ()
{
this.$el.html('');
console.log(this.collection);
this.collection.each( function ( song )
{
var songItem = new SongView( { model: song } );
this.$el.append( songItem.el );
}, this);
}
更新
这是我的路由代码:
define([
'jQuery',
'Underscore',
'Backbone',
'views/start',
'views/playlist'
],
function ($, _, Backbone, startView, playlistView)
{
var AppRouter = Backbone.Router.extend({
routes: {
'playlist': 'playlist',
// default
'*actions': 'start'
},
start: function ()
{
// call render on the module we loaded via the dependency array
// views/items/list
startView.render();
},
playlist: function ()
{
playlistView.render();
},
defaultAction: function ( actions )
{
// no default action, let's just log what the url was
console.log('No route:', actions)
}
});
var initialize = function ()
{
var app_router = new AppRouter;
Backbone.history.start();
}
return {
initialize: initialize
};
}
);