[英]Change page view with Backbone
我已经使用Backbone.js在我的一页应用程序中实现了“更改页面”。 但是,我不确定我的路由器是否应包含太多业务逻辑。 我是否应该考虑使用Marionette.js来实现这种功能并使我的路由器变薄? 我是否应该担心在更改它时会破坏附加到“上一个”活动页面/视图上的Backbone模型和视图(以避免内存泄漏),还是足以清空附加到那些模型/视图上的html。 这是我的路由器:
App.Router = Backbone.Router.extend({
routes: {
'users(/:user_id)' : 'users',
'dashboard' : 'dashboard'
},
dashboard: function() {
App.ActiveView.destroy_view();
App.ActiveViewModel.destroy();
App.ActiveViewModel = new App.Models.Dashboard;
App.ActiveViewModel.fetch().then(function(){
App.ActiveView = new App.Views.Dash({model: App.ActiveViewModel });
App.ActiveView.render();
});
},
users: function(user_id) {
App.ActiveView.destroy_view();
App.ActiveViewModel.destroy();
App.ActiveViewModel = new App.Models.User;
App.ActiveViewModel.fetch().then(function() {
App.ActiveView = new App.Views.UsersView({model: App.ActiveViewModel});
App.ActiveView.render();
});
}
});
另一种方法:
创建一个AbstractView
声明一个AbstractView
,然后从AbstractView
扩展您的其他应用程序特定的View's
具有许多优点。 您始终拥有一个可以放置所有常用功能的View
。
App.AbstractView = Backbone.View.extend({
render : function() {
App.ActiveView && App.ActiveView.destroy_view();
// Instead of destroying model this way you can destroy
// it in the way mentioned in below destroy_view method.
// Set current view as ActiveView
App.ActiveView = this;
this.renderView && this.renderView.apply(this, arguments);
},
// You can declare destroy_view() here
// so that you don't have to add it in every view.
destroy_view : function() {
// do destroying stuff here
this.model.destroy();
}
});
您的App.Views.UsersView
应该从AbstractView
扩展,并renderView
App.Views.UsersView
代替render
因为AbstractView's
render将调用renderView
。 您可以从Router
调用render
,方法与App.ActiveView.render();
相同App.ActiveView.render();
App.Views.UsersView = AbstractView.extend({
renderView : function() {
}
// rest of the view stuff
});
App.Views.Dash = AbstractView.extend({
renderView : function() {
}
// rest of the view stuff
});
路由器代码将更改为:
dashboard: function() {
App.ActiveViewModel = new App.Models.Dashboard;
App.ActiveViewModel.fetch().then(function(){
new App.Views.Dash({model: App.ActiveViewModel }).render();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.