我正在开发一个backbone.js-application,并且已经达到了我有许多代表我的应用程序的每个部分的路由器和视图的程度.在下面简化的路由器示例中,我有两个位置;帐号&用户.
每个位置的两个视图都将其内容呈现为一个名为#appcontainer的共同元素.我的常识说我应该在启动另一个视图之前确保每个视图remove
以防止绑定,DOM和诸如此类的冲突.
但由于我无法确定是否已创建视图,因此我无法从路由器或视图中显式调用prevIoUsView.remove().
将$(this.el).empty()添加到每个视图的构造函数以清除DOM中的任何最终先前绑定和元素是否足够?
这是路由器示例?
- var myRouter = Backbone.Router.extend({
- routes: {
- "account": "account","users": "users"
- },account: function() {
- view = new AccountView({});
- view.render();
- },users: function() {
- view = new UserView({});
- view.render();
- }
- });
解决方法
我有一个非常简单的实现,我现在只是启动我的应用程序,并且不知道从长远来看这将如何保持,但它看起来像这样:
编辑:这是整个文件的样子. this.render将是myRouter的另一个功能.
- var myRouter = Backbone.Router.extend({
- routes: {
- 'path/to/account' : 'account','path/to/users': 'users'
- }
- account: function() {
- view = new AccountView({});
- this.render(view);
- },users: function() {
- view = new UserView({});
- this.render(view);
- },render: function (view) {
- //Close the current view
- if (this.currentView) {
- this.currentView.remove();
- }
- //render the new view
- view.render();
- //Set the current view
- this.currentView = view;
- return this;
- }
- });