该代码每次都有效,除非第一次调用路由器并加载页面。,集合已创建,但未填充notes.fetch();
. 我一直在寻找,我不明白为什么会发生这种情况。
例如,当我转到 URL 加载此页面时,除了集合中的内容之外的所有内容都会加载。当我进入#blank/' and then go "Back" to the
列表视图时,集合和模型会按预期加载。那么如何在页面加载后加载集合?
这是代码:
$(function() {
// Note: The model and collection are extended from TastypieModel and TastypieCollection
// to handle the parsing and URLs
window.Note = TastypieModel.extend({});
window.Notes = TastypieCollection.extend({
model: Note,
url: NOTES_API_URL
});
window.notes = new Notes();
window.NoteView = Backbone.View.extend({
className: "panel panel-default note",
template: _.template($('#notes-item').html()),
events: {
'click .note .edit': 'editNoteToggle',
'click .note .edit-note': 'doEdit'
},
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
editNoteToggle: function() {
console.log("I've toggled the edit box");
},
doEdit: function() {
console.log('This will edit the note');
}
});
window.NoteListView = Backbone.View.extend({
el: "#app",
template: _.template($('#notes-item-list').html()),
events: {
'click #add-note': 'addNote'
},
initialize: function () {
_.bindAll(this, 'render', 'addNote');
this.collection.bind('change', this.render);
},
render: function() {
this.$el.html(this.template());
console.log('before the loop');
console.log(this.collection.toJSON()); //<- Empty when it first loads, then contains the models when I visit another page and come "back" to this page
this.collection.each(function(note){
var view = new NoteView({ model: note });
$('#notes-list').append(view.render().el);
});
console.log('done');
$('#add-note-toggle').on('click', this, function() {
$('#note-add-form').toggle();
});
return this;
},
addNote: function() {
console.log('The add note was clicked');
}
});
window.NotesRouter = Backbone.Router.extend({
routes: {
'': 'list',
'blank/': 'blank'
},
initialize: function() {
// starts by assigning the collection to a variable so that it can load the collection
this.notesView = new NoteListView({
collection: notes
});
notes.fetch();
},
list: function () {
$('#app').empty();
$('#app').append(this.notesView.render().el);
},
blank: function() {
$('#app').empty();
$('#app').text('Another view');
}
});
window.notesRouter = new NotesRouter();
Backbone.history.start();
})