[英]how to switch views with the backbone.js router?
就使用骨干路由器和骨干网中的渲染视图而言,这更像是一个概念性问题。
为了一个例子(我正在构建以学习这个)我有一个基本的CRUD应用程序的联系人,创建表单,所有联系人列表,联系人单一视图和编辑表单。
为了简单起见,我会说我只想一次看到其中一件事。 显然用jQuery显示和隐藏它们将是微不足道的,但那不是我追求的。
我有两个想法,
1)从我的路由器触发自定义事件,删除所有视图并发送可在所有视图中侦听的事件(触发close方法)和主App视图,然后实例化特定视图 - 即:
App.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'addnew' : 'addNew',
'contacts/:id' : 'singleContact',
'contacts/:id/edit' : 'editContact'
},
index: function(){
vent.trigger('contactR:closeAll');
vent.trigger('contactR:index');
},
addNew: function() {
vent.trigger('contactR:closeAll');
vent.trigger('contactR:addNew');
},
singleContact: function(id) {
vent.trigger('contactR:closeAll');
vent.trigger('contactR:singleContact', id);
},
editContact: function(id) {
vent.trigger('contactR:closeAll');
vent.trigger('contactR:editContact', id);
},
});
(nb:vent正在扩展骨干事件obj所以我可以发布/ sub)
2)或将/可能/我应该发送关闭所有事件并在路由器中创建视图的实例?
注意我正在寻求实现这一点,而不是钻研其他库或框架,如木偶等。
您可以使用这样的实用程序对象:
var ViewManager = {
currentView : null,
showView : function(view) {
if (this.currentView !== null && this.currentView.cid != view.cid) {
this.currentView.remove();
}
this.currentView = view;
return view.render();
}
}
每当您想要显示视图时,请使用ViewManager.showView(yourView)
App.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'addnew' : 'addNew',
'contacts/:id' : 'singleContact',
'contacts/:id/edit' : 'editContact'
},
index: function(){
var indexView ...
ViewManager.showView(indexView);
},
addNew: function() {
var addNewView ...
ViewManager.showView(addNewView);
},
singleContact: function(id) {
var singleContactView ...
ViewManager.showView(singleContactView);
},
editContact: function(id) {
var editContactView ...
ViewManager.showView(editContactView);
},
});
因此,ViewManager负责渲染您的视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.