Javascript 使用“后退”按钮时delegateEvents未按预期工作
下面是我的主要观点Javascript 使用“后退”按钮时delegateEvents未按预期工作,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,下面是我的主要观点 define([ 'app', 'backbone', 'twig', 'templates/report', 'data/reportViewCollection', 'data/reportViewModel' ], function (app, Backbone, Twig, template, Collection, Model) { var collection = new Collection();
define([
'app',
'backbone',
'twig',
'templates/report',
'data/reportViewCollection',
'data/reportViewModel'
], function (app, Backbone, Twig, template, Collection, Model) {
var collection = new Collection();
var fetching;
return Backbone.View.extend({
setParams: function (rlId, viewId, categoryId, depth) {
// reset any possible pending previous repests.
fetching = false;
var model = collection.getModel(rlId, viewId, categoryId, depth);
if (!model) {
model = new Model({
rlId: rlId,
viewId: viewId,
categoryId: categoryId,
depth: depth
});
fetching = model.fetch({
success: function (model) {
collection.add(model);
},
error: function (model) {
alert('error getting report view');
}
});
}
this.model = model;
},
render: function () {
var that = this;
var done = function() {
app.vent.trigger('domchange:title', that.model.get('title'));
that.$el.html(Twig.render(template, that.model.toJSON()));
that.delegateEvents(that.events);
fetching = false;
};
if (fetching) {
app.loading(this);
fetching.done(done);
} else {
done();
}
return this;
},
events: {
'change select.view-select': 'viewSelect',
'click #dothing': function (e) {e.preventDefault(); alert('hi');}
},
viewSelect: function(e) {
var selectedView = $(e.target).val();
var rlId = this.model.get('rlId');
if (!rlId) rlId = 0;
var url = 'report/' + rlId + '/' + selectedView;
console.log(this, e, url);
Backbone.history.navigate(url, {trigger: true});
}
});
});
功能说明:
当导航到特定url时,会调用setParams()
函数从服务器获取模型。当调用render方法时,它会检查我们当前是否正在获取模型,如果是,则在完成获取时使用set延迟回调来呈现模板。当模型被提取并准备好渲染时,渲染模板并通过that.$el.html()
填充视图
问题:
发生的事情是,我的事件在我第一次导航到url时工作得很好,但当我点击后退按钮时,我的事件不会被连接
我已经仔细检查了代码,看不出有什么不同。唯一真正的区别是,我立即从缓存的集合
加载模型,而不是执行ajax请求来获取它
有什么线索吗?尝试改变:
that.$el.html(Twig.render(template, that.model.toJSON()));
到
我遇到了同样的问题,这就解决了。我解决了我的问题。@mu的评论为我指明了正确的方向 我正在使用,并且我的视图包含在一个区域中。在Region的open函数中,它正在执行
this.$el.html(view.el)代码>在某些情况下清除事件。我仍然不知道为什么它会在一些人身上出现,但在另一些人身上却会出现
解决方案是在我的视图中添加一个onShow
函数,调用this.delegateEvents()
。现在一切都很顺利
我最终通过单步执行代码并查看视图div上注册的事件来解决这个问题。如何渲染视图?我想知道你是否看到了这种情况的变体:谢谢@muistooshort,你为我指明了正确的方向。
that.$el.html("");
that.$el.append(Twig.render(template, that.model.toJSON()));