[编辑:我通过调用 delegateEvents() 解决了之前的问题,但不必这样做。重新发布并提供更多信息。]
我有一个 View ,渲染时其上有一个登录按钮,并附加了单击事件。首先渲染所有作品:单击按钮,成功调用 ajax 后,登录提示消失并显示欢迎 View (LoggedInView)。但是,如果我稍后导航回此 View (#foo),UI 将呈现,但事件关联消失,而无需通过调用 delegateEents() 手动强制解决问题。
我的事件没有重新关联,这是怎么回事?
LoginView = Backbone.View.extend({
template: _.template($("#loginTemplate").html()),
initialize: function(stuff,router) {
_.bindAll(this,'render','rc','gotProfile');
this.model.bind("rc",this.rc)
this.router = router;
},
events: {
'click .loginButton': 'login'
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
$(this.el).find(".actionButton").button(); // Button
// this.delegateEvents(this.events); // NEEDED! Re-wire events on re-render
return this;
},
rc: function(code) {
switch(code) {
case errCodes.USER_NOT_FOUND: this.notFound(); break;
case errCodes.OK: this.loginOk(); break;
default: this.otherErr(); break;
}
},
login: function() {
clearErrors( $('[rel="req"]') );
var okReq = validate( $('#login [rel="req"]'), validateReq );
var okEmail = validate( [$('#uid')], validateEmail );
if( okReq && okEmail ) {
this.model.set({'uid':$('#uid').val().trim(), 'pwd':$('#pwd').val().trim()});
this.model.fetch();
}
},
notFound: function() {
validate( [$('#uid'),$('#pwd')], function(){return[false,"Invalid user / password"]} );
},
otherErr: function() {
validate( [$('#uid'),$('#pwd')], function(){return[false,"Please contact support for help logging in."]} );
},
loginOk: function() {
this.profile = new Profile({uid:this.model.get('uid'),token:this.model.get('key')});
this.profile.bind("rc",this.gotProfile)
this.profile.fetch();
},
gotProfile: function() {
this.router.navigate('/',true);
}
});
LoggedInView = Backbone.View.extend({
template: _.template($("#loggedInTemplate").html()),
uList: new ProfileList(),
initialize: function() {
_.bindAll(this,'render','renderUserList','renderUser');
this.model.bind('show', this.render);
this.uList.bind('rc', this.render);
},
events: {
'click #ufa': 'getUsersForHouse'
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.renderUserList();
// this.delegateEvents(this.events); // NEEDED! Re-wire events on re-render
return this;
},
renderUserList: function() {
$(this.el).find('ul').empty();
this.uList.each(this.renderUser);
},
renderUser: function(aUser) {
$(this.el).find('#userList').append("<li>"+aUser.get('person').firstName+"</li>");
},
getUsersForHouse: function() {
this.uList.fetch(this.model.get('token'),"house");
}
});
Main = Backbone.Router.extend({
routes: {
'foo': 'foo',
'*all': 'home'
},
initialize: function() {
this.token = new Token();
this.loginView = new LoginView({model:this.token},this);
},
foo: function(){ // naving here looses click event on login button
$('#login').empty();
$("#login").append(this.loginView.render().el);
},
home: function() {
$('#login').empty();
if( this.loginView.profile == null )
$("#login").append(this.loginView.render().el);
else {
this.loggedInView = new LoggedInView({model:this.loginView.profile});
$("#login").append(this.loggedInView.render().el);
}
}
});
最佳答案
您清空了#login div。正如 jQuery 文档所说:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
因此,您实际上是从 View 中删除了事件。我更喜欢使用分离,因为它可以保留事件。 http://api.jquery.com/detach/
您可以在 View 中实现显示/隐藏来处理此问题。
关于events - 重新渲染后,backbone.js 事件不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348988/