我正在尝试理解骨干网,目前正在与僵尸观点作斗争。我已经阅读了很多关于这个问题的堆栈溢出帖子,但我仍然无法弄清楚。
为了简单起见,我设置了两个需要切换的视图(没有数据)。
到目前为止我所做的是:
- 创建对象
//定义应用对象
变种应用程序 = {
发泄:{},
模板:{},
意见:{},
路由器:{},
};
//实例化事件聚合器并将其附加到应用程序
app.vent = _.extend({}, Backbone.Events);
定义两个非常简单的模板(存储在 app.templates 中):第一个有一些虚拟文本和一个按钮(带有和 id 为 'test-begin'),第二个只是虚拟文本
定义两个视图
app.views.instructions = Backbone.View.extend({
//加载下划线模板
模板:_.template(app.templates.instructions),
//实例化时自动调用
初始化:函数(选项){
//将相关函数绑定到视图
_.bindAll(this, 'render', 'testBegin', 'stillAlive', 'beforeClose');
//监听app.vent事件
this.listenTo(app.vent, 'still:alive', this.stillAlive);
},
//将事件绑定到DOM元素
事件:{
'点击#test-begin' : 'testBegin',
},
//渲染视图
渲染:函数(){
this.$el.html(this.template());
返回这个;
},
//开始考试
测试开始:函数(){
Backbone.history.navigate('begin', {trigger: true});
},
//还活着
仍然活着:函数(){
console.log('我还活着');
},
//关闭前
关闭前:函数(){
//停止监听 app.vent
this.stopListening(app.vent);
},
});
//测试视图
app.views.test = Backbone.View.extend({
//加载下划线模板
模板:_.template(app.templates.test),
//实例化时自动调用
初始化:函数(选项){
//触发 still:alive 并查看移除的视图是否响应它
app.vent.trigger('still:alive');
//将相关函数绑定到视图
_.bindAll(this, 'render');
},
//渲染视图
渲染:函数(){
this.$el.html(this.template());
返回这个;
},
});
- 定义路由器
//基础路由器
app.routers.baseRouter = Backbone.Router.extend({
//路线
路线:{
'': “指示”,
“开始”:“开始测试”
},
//函数(属于对象控制器)
指令:函数(){baseController.instructions()},
开始测试:函数(){baseController.beginTest()},
});
//baseRouter控制器
var baseController = {
说明:函数(){
mainApp.viewsManager.rederView(new app.views.instructions());
},
开始测试:功能(选项){
mainApp.viewsManager.rederView(new app.views.test());
},
};
- 定义 mainApp(带有视图切换器)
//定义mainApplication对象
主应用程序 = {};
//管理视图切换
mainApp.viewsManager = {
//rootEl
rootEl: '#test-container',
//关闭当前视图并显示下一个
rederView:功能(视图,rootEl){
//如果没有传递DOM el,则将其设置为默认的RootEl
rootEl = rootEl ||这个.rootEl;
//关闭当前视图
if (this.currentView) this.currentView.close();
//存储对下一个视图的引用
this.currentView = 视图;
//渲染下一个视图
$(rootEl).html(this.currentView.render().el);
},
};
//渲染应用程序的第一个视图
mainApp.viewsManager.rederView(new app.views.instructions());
//启动路由器并将其附加到应用程序
mainApp.baseRouter = new app.routers.baseRouter();
//开始骨干网历史
Backbone.history.start({沉默:真
});
- 添加关闭功能以通过 Backbone 原型查看
//向Backbone视图原型添加函数(在所有视图中可用)
Backbone.View.prototype.close = function () {
//调用view beforeClose函数,如果它在视图中定义
if (this.beforeClose) this.beforeClose();
//this.el 从 DOM 中移除 & DOM 元素的事件被清理
this.remove();
//取消绑定视图绑定的任何模型和集合事件
this.stopListening();
//检查视图是否有子视图
if (this.hasOwnProperty('_subViews')) {
//遍历当前视图的子视图
_(this._subViews).each(function(child){
//调用子视图的关闭方法
child.close();
});
}
};
因此,为了检查僵尸视图,第二个视图触发和事件 (still:alive) 第一个视图监听并通过发送到 console.log 的消息响应它(尽管它确实不应该)。
第一个视图确实会听到这样的消息(在控制台日志中我读到“我还活着),即使它已被第二个视图替换。
你能帮帮我吗?非常感谢。