找到了合适的解决方案。在启动主干应用程序之前,我在新函数 loadDataAndStartApp() 中检索 JSON 数据。当 dom 准备好时加载此函数,一旦加载 JSON,它就会启动主干应用程序。这样您就可以确定所有可用数据。连同 nemesv 所说的关于创建新类别功能的内容以及他回答中的其他建议,我为这个问题制定了以下答案。
var AppRouter = Backbone.Router.extend({
routes: {
"": "startscreen",
"Onderwerpen": "subjectsList"
},
initialize: function (options) {
this.categories = new Categories( options.categories );
this.subjectsListView2 = new SubjectsListView({
collection: new Categories(
this.categories.where({ parent : null, name : "Evenwicht" })
)
});
//view for spacesList
},
startscreen: function () {
$('#app').html(this.startscreenView.render().el);
},
subjectsList: function () {
$('#app').append(this.subjectsListView2.render().el);
},
});
function loadDataAndStartApp(){
var categories = []
// LOAD APP DATA
$.ajax({
url : './catalogue.json',
dataType : 'json'
}).done(function(data){
console.log('Catalogue retrieved');
// GET CATEGORIES
_.each(data.categories, function( categorieObj ){
var categorieName = _.keys(categorieObj)[0],
categorieAttributes = categorieObj[categorieName];
categories.push( categorieAttributes );
});
// START APP
var app = new AppRouter({
categories : categories
});
Backbone.history.start();
});
}
$(function(){
// ON DOM READY
loadDataAndStartApp();
});