我的路由器中有一个addPost
功能。我不想在postAddView
每次调用函数时重新创建:
addPost: function () {
var that = this;
if (!this.postAddView) {
this.postAddView = new PostAddView({
model: new Post()
});
this.postAddView.on('back', function () {
that.navigate('#/post/list', { trigger: true });
});
}
this.elms['page-content'].html(this.postAddView.render().el);
}
这是 PostAddView:
PostAddView = backbone.View.extend({
events: {
'click #post-add-back': 'back'
}
, back: function (e) {
e.preventDefault();
this.trigger('back');
}
});
第一次渲染 postAddView 时,事件触发器运行良好。但是,在渲染其他视图page-content
并渲染postAddView
回来之后,事件触发器将不再被触发。不过,以下版本的addPost
效果很好。
addPost: function () {
var that = this, view;
view = new PostAddView({
model: new Post()
});
this.elms['page-content'].html(view.render().el);
view.on('back', function () {
delete view;
that.navigate('#/post/list', { trigger: true });
});
}