【发布时间】:2013-05-25 20:36:54
【问题描述】:
我已经扩展了 Backbone 的 View 原型以包含一个“关闭”功能以“杀死僵尸”,这是我从 Derrick Bailey's blog 学到的技术
代码如下所示:
Backbone.View.prototype.close = function () {
this.remove();
this.unbind();
if (this.onClose) {
this.onClose();
}
};
然后我有一个看起来(大部分)像这样的路由器:
AppRouter = Backbone.Router.extend({
initialize: function() {
this.routesHit = 0;
//keep count of number of routes handled by your application
Backbone.history.on('route', function () { this.routesHit++; }, this);
},
back: function () {
if(this.routesHit > 1) {
//more than one route hit -> user did not land to current page directly
logDebug("going window.back");
window.history.back();
} else {
//otherwise go to the home page. Use replaceState if available so
//the navigation doesn't create an extra history entry
this.navigate('/', {trigger:true, replace:true});
}
},
routes: {
"": "showLoginView",
"login": "showLoginView",
"signUp": "showSignUpView"
},
showLoginView: function () {
view = new LoginView();
this.render(view);
},
showSignUpView: function () {
view = new SignUpView();
this.render(view);
},
render: function (view) {
if (this.currentView) {
this.currentView.close();
}
view.render();
this.currentView = view;
return this;
}
});
我的 LoginView 的渲染函数是这样的:
render: function () {
$("#content").html(this.$el.html(_.template($("#login-template").html())));
this.delegateEvents();
return this;
}
第一次渲染 LoginView 时,效果很好。但是,如果我渲染一个不同的视图(从而在我的 LoginView 上调用“关闭”)然后尝试返回我的 LoginView,我会得到一个空白屏幕。我知道我的 LoginView 上的渲染第二次触发的事实,但似乎我的“关闭”方法导致了问题。有什么想法吗?
编辑在 Rayweb_on 的一些反馈之后,看来我应该添加更多细节并澄清。
我的 HTML 如下所示:
<div id="header">this is my header</div>
<div id="content">I want my view to render in here</div>
<div id="footer">this is my footer</div>
然后我有一个看起来像这样(有点)的登录模板:
<script type="text/template" id="login-template">
<div id="login-view">
<form>
...
</form>
</div>
</script>
我试图让视图始终呈现在该“内容”div 内,但似乎对“关闭”的调用有效地从 DOM 中删除了“内容”div。因此是“空白”页面。有什么想法吗?
编辑 2 这是我的 LoginView 的样子,经过一番折腾:
LoginView = Backbone.View.extend({
events: {
"vclick #login-button": "logIn"
},
el: "#content",
initialize: function () {
_.bindAll(this, "logIn");
},
logIn: function (e) {
...
},
render: function () {
this.$el.html(_.template($("#login-template").html()));
this.delegateEvents();
return this;
}
});
我将 el 设置为“#content”,希望它会被重新创建。但仍然没有运气。事实上,现在当我转到下一页时,它不存在,因为 #content 正在被立即删除。
我也试过了:
LoginView = Backbone.View.extend({
events: {
"vclick #login-button": "logIn"
},
el: "#login-template",
initialize: function () {
_.bindAll(this, "logIn");
},
logIn: function (e) {
...
},
render: function () {
this.$el.html(_.template($("#login-template").html()));
this.delegateEvents();
return this;
}
});
但这根本行不通。有什么想法吗?
【问题讨论】:
标签: backbone.js view underscore.js render