这是来自Backbone 样板的后续问题:“this.model is undefined”。我能够解决一些结构,但遇到了一个新问题。我正在使用骨干样板,它使用 layoutManager 适配器来设置视图。主视图以及随后的第一个视图似乎正在正确加载所有资产,尽管后续视图似乎在主视图加载之前触发。这是我的路由器文件:
define([
// Application.
"app",
//Modules
"modules/homepage"
],
function (app, Homepage) {
"use strict";
// Defining the application router, you can attach sub routers here.
var Router = Backbone.Router.extend({
initialize: function(){
var collections = {
homepage: new Homepage.Collection()
};
_.extend(this, collections);
app.useLayout("main-frame").setViews({
".homepage": new Homepage.Views.Index(collections)
}).render();
},
routes:{
"":"index"
},
index: function () {
this.reset();
},
// Shortcut for building a url.
go: function() {
return this.navigate(_.toArray(arguments).join("/"), true);
},
reset: function() {
// Reset collections to initial state.
if (this.homepage) {
this.homepage.reset();
}
// Reset active model.
app.active = false;
}
});
return Router;
}
);
这是我的模块:
define([
"app",
["localStorage"]
],
function(app){
"use strict";
var Homepage = app.module();
Homepage.Model = Backbone.Model.extend({
defaults: function(){
return {
homepage: {}
};
}
});
Homepage.Collection = Backbone.Collection.extend({
//localStorage: new Backbone.LocalStorage("Homepage.Collection"),
refreshFromServer: function() {
return Backbone.ajaxSync('read', this).done( function(data){
console.log(data);
//save the data somehow?
});
},
/*model: Homepage.Model,*/
cache: true,
url: '/app/json/test.json',
initialize: function(options){
if (options) {
this.homepage = options.homepage;
}else{
//this.refreshFromServer();
}
}
});
Homepage.Views.Index = Backbone.View.extend({
template: "homepage",
el: '#mainContent',
serialize: function() {
return {
collection: this.options.homepage
};
},
initialize: function(){
this.listenTo(this.options.homepage,{
"reset": this.render,
"fetch": function(){
$(this.el).html("Loading...");
}
});
}
});
return Homepage;
});
如您所见,“main-frame”模板是加载到页面中的主模板。我希望稍后加载主页模板,该模板将填充到 ID“#mainContent”中。但在这种情况下,“#mainContent”还不存在,因此主页模板不会加载到任何地方。