var LandingView = Backbone.View.extend({
initialize: function() {
console.log('Landing View has been initialized');
this.render();
},
template: Handlebars.compile($('#landingPage').html()),
render: function() {
this.$el.html(this.template);
},
events: {
// I want to render the subview on click
'click .btn-login' : 'renderlogin',
},
renderlogin: function() {
// Is this the right way to instantiate a subview?
var loginpage = new LoginView({ el: $('#modal-content') });
}
});
而我的下一个视图,基本上只是清空了 $('#modal-content') 元素......
var LoginView = Backbone.View.extend({
initialize: function() {
this.render();
console.log("login view initialized");
},
template: Handlebars.compile($('#loginPage').html()),
render: function() {
this.delegateEvents();
this.$el.html(this.template);
},
events: {
// this is where things get super confusing...
// Upon clicking, LoginView gets re-initialized and
// subsequent clicks are called for each number of times
// the view is initialized.
'click .js-btn-login' : 'login'
},
login: function(e) {
e.preventDefault();
var self = this;
console.log($(this.el).find('#userSignIn #userEmail').val());
console.log($(this.el).find('#userSignIn #userPassword').val());
}
});
我的模板:
登陆页面:
<script type="text/x-handlebars-template" id="landingPage">
<div>
<div class="auth-wrapper">
<div class="logo">
<img src="img/login/logo-landing.png"/>
</div>
<div class="to-auth-buttons-wrapper">
<a class="btn-to-auth btn-signup" href="#">Sign Up</a>
<a class="btn-to-auth btn-login" href="#">Log In</a>
</div>
</div>
</div>
</script>
登录页面:
<script type="text/x-handlebars-template" id="loginPage">
<div>
<div class="header">
<a href="#" class="btn back-to-landing">Back</a>
</div>
<div class="auth-wrapper">
<div class="logo">
<img src="img/login/logo-landing.png"/>
</div>
<form method="post" id="userSignIn">
<input class="form-control input-signin" type="text" name="useremail" placeholder="Email" id="userEmail" value="tester">
<input class="form-control input-signin" type="password" name="userpass" placeholder="Password" id="userPassword">
<button class="btn-to-auth btn-login js-btn-login">Log In</button>
</form>
</div>
</div>
</script>
我的目标:
在 LandingView 中,单击 .btn-login 后,呈现 LoginView。
在 LoginView 中,单击 .js-btn-login,console.log 表单的内容
问题:
- 在 LoginView 中,单击 .js-btn-login 后,我看到再次调用了初始化函数。
- 在 LoginView 中,我不能使用 jquery 来获取 $('#userSignIn #userEmail').val() 和 $('#userSignIn #userEmail').val() 中的值,因为它们不在渲染中. 我看到了初始硬编码值 (
input[value="tester"]
),但这就是它所看到的全部。
我的问题:
如何让视图在事件触发时停止重新初始化,以及如何在渲染后获取 DOM 中的值?