我试图通过将更改事件绑定到视图模型来让视图自我呈现。我在 PageView 上创建了一个自定义函数,它将 Pages 集合中的模型作为参数,并使用 this.model.set(data) 来触发模型更改事件。当我通过 this.page.load(Pages.at(index)) 将 AppView 中的 Pages 集合中的 Page 模型传递给它时,就会触发这种情况。我遇到了一些问题。
- change 事件仅在 2 个不同模型之间来回切换时触发一次,我可以通过运行 this.model.clear({silent:true}) 来解决这个问题,但这并不理想。
- this.model 在除 PageView 中的 load() 函数之外的任何函数中始终未定义,这确实是主要问题,因为如果模型未定义,我显然无法触发 this.render。因此测试:函数()。
无论如何,这是我的 AppView 和 PageView 函数的代码。提前感谢您的帮助。
define([
// These are path alias that we configured in our bootstrap
'jquery',
'underscore',
'backbone',
'handlebars',
'views/pageView',
'views/menuView',
'collections/pages'
], function($, _, Backbone, Handlebars,PageView,MenuView,Pages){
var AppView = Backbone.View.extend({
//Stores a reference to our main menu
mainMenu:{},
//Stores reference to current page
page:{},
//The parent div
el:'#app',
//Events that are being listened to on #app
events:{"click" : "active"},
//Process to run when this view is initialized
initialize:function(){
//Load our Pages Collection
Pages.reset(this.model.pages);
//Load the main menu
this.mainMenu = new MenuView;
this.mainMenu.model = this.model.main_menu;
this.mainMenu.render();
//Loads the page view
this.page = new PageView({model:Pages.at(0)});
},
//Currently just renders a page view with a designated model from the Pages collection
render:function(index){
this.page.load(Pages.at(index));
},
active:function(event){
$('.menu a').removeClass('active');
$('.menu a[href="' + event.target.hash + '"]').addClass('active');
}
});
return AppView;
// What we return here will be used by other modules
});
define([
// These are path alias that we configured in our bootstrap
'jquery',
'underscore',
'backbone',
'handlebars',
'text!templates/page.html',
], function($, _, Backbone, Handlebars, pageViewTemplate){
var PageView = Backbone.View.extend({
//Define the default template
template: Handlebars.compile(pageViewTemplate),
//The parent div for this element
el:'#content',
initialize:function(){
this.model.bind('change',this.test);
},
load:function(data){
this.model.set(data);
},
//Render function
render:function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
test:function(){
console.log(this.model);
console.log('change');
}
});
return PageView;
// What we return here will be used by other modules
});