我有某种 ViewCollection 可以呈现所有子视图。
define(
['jquery', 'underscore', 'backbone', 'text!templates/main/layout.html', 'text!templates/main/index.html', 'views/security/login', 'views/security/registration'],
function($, _, Backbone, LayoutTemplate, ContentTemplate, LoginView, RegistrationView) {
var IndexView = Backbone.View.extend({
tagName: "div",
className: "container",
template: LayoutTemplate,
render: function() {
this.$el.html(LayoutTemplate);
this.$('div.content').html(ContentTemplate);
this.$('div.sidebar').append(new LoginView().render().el);
this.$('div.sidebar').append(new RegistrationView().render().el);
return this;
}
});
return IndexView;
});
这很好用!不幸的是,我注意到例如 LoginView 不能再处理事件了。
define(
['jquery', 'underscore', 'backbone', 'text!templates/security/login.html'],
function($, _, Backbone, LoginTemplate){
var LoginView = Backbone.View.extend({
tagName: "form",
className: "login well",
template: LoginTemplate,
events: {
"submit form.login": "submit"
},
render: function(){
this.$el.html(this.template);
return this;
},
submit: function(e){
e.preventDefault();
var credentials = {
'username': $(e.target[1]).val()
, 'password': $(e.target[2]).val()
};
console.log(JSON.stringify(credentials));
$.ajax({
url: '/session'
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(credentials)
, success: function() {
window.Router.navigate('node', { trigger: true });
}
, error: function(xhr, status, error) {
console.log([xhr, status, error]);
$(e.target[1]).closest('div.control-group').addClass('error');
$(e.target[2]).closest('div.control-group').addClass('error');
}
});
}
});
return LoginView;
});
浏览器没有发送 ajax 调用,而是尝试提交表单数据 url 编码为 GET 请求,这表明视图不再监听任何视图......
是否可以选择如何将视图事件重新绑定到元素?
登录.html
<fieldset>
<legend>login</legend>
<div class="control-group">
<label class="control-label" for="_session_username">username:</label>
<div class="controls">
<input type="text" id="_session_username" name="session[username]" placeholder="george78" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="_session_password">password:</label>
<div class="controls">
<input type="password" id="_session_password" name="session[password]" placeholder="••••••" />
</div>
</div>
<button type="submit" class="btn btn-primary">login</button>
</fieldset>
表单标签也在视图中定义 .login 类属性。