修改
我将一个console.log放在主视图的获取成功回调中(#/)。这些是每次加载页面时提取的cid ID。你可以看到最后在原始页面加载时只有一个获取请求,只有一个。
/#: c2
/#link1 + back button: c4, c2
/#link1 + back button: c4, c2, c2, c2
/#link2 + back button: c4, c2, c2, c2, c2, c2
原始
我在骨干网中遇到一个奇怪的错误,后退按钮导致ajax请求重复。如果我转到#/
,然后点击#/link
这两个都会让他们的ajax请求变好。问题是当我点击后退按钮返回#/
时。它使正常的ajax请求但是两次。如果我每次按下后退按钮重复此过程,它会增加重复请求的数量(1个原始+后退按钮的数量):2个后退按钮推送= 3个ajax请求,3个后退按钮推送= 4个ajax请求
即使我在视图上使用完全不同的链接(在我使用了后退按钮之后),它也会复制该视图的ajax请求。如果我只是点击链接而不使用后退按钮,则不会发生错误。
我在路由器中使用AppView来清理旧视图并加载新视图。这会调用Backbone.View.prototype.close,后者又调用View.close。我认为这听起来很合理,但想包括以防万一。
之前有没有经历过这个?
APPVIEW
function AppView () {
this.view = null;
this.showView = function (view, renderOpts) {
renderOpts = (typeof renderOpts === 'undefined') ? {} : renderOpts;
if (this.view) this.view.close();
this.view = view;
$('.view').html(this.view.render(renderOpts).el);
}
}
Backbone.View.prototype.close
Backbone.View.prototype.close = function () {
this.remove();
this.unbind();
if (this.onClose) this.onClose();
};
路由器
var Router = Backbone.Router.extend({
routes: {
'': 'home',
'compound_interests/new': 'editCompoundInterest',
'compound_interests/:id': 'viewCompoundInterest',
'compound_interests/:id/parameters': 'compoundInterestParametersEditor',
'compound_interests/:id/test': 'compoundInterestTester',
'compound_interests/:id/stream': 'compoundInterestStreamer'
},
initialize: function (opts) {
this.appView = opts.appView;
},
home: function () {
var view = new HomeView();
this.appView.showView(view);
},
editCompoundInterest: function () {
var view = new EditCompoundInterestView();
this.appView.showView(view);
},
viewCompoundInterest: function (id) {
var view = new ViewCompoundInterestView({ id: id });
this.appView.showView(view);
},
compoundInterestParametersEditor: function (id) {
var view = new CompoundInterestParametersEditorView({ id: id });
this.appView.showView(view);
},
compoundInterestTester: function (id) {
var view = new CompoundInterestTesterView({ id: id });
this.appView.showView(view);
},
compoundInterestStreamer: function (id) {
var view = new CompoundInterestStreamerView({ id: id });
this.appView.showView(view);
}
});
router = new Router({ appView: new AppView() });
主页视图
var Backbone = require('backbone'),
_ = require('lodash');
var CompoundInterests = require('../collections/compound_interests');
module.exports = Backbone.View.extend({
initialize: function () {
var that = this;
_.bindAll(this, 'render');
this.template = JST['templates/home'];
this.context = { data: {} };
this.compoundInterests = new CompoundInterests();
this.compoundInterests.on('sync', this.render);
this.compoundInterests.fetch();
},
onClose: function () {
this.compoundInterests.off('sync');
this.render();
},
render: function () {
this.context.data.compoundInterests = _.clone(this.compoundInterests.models);
this.$el.html(this.template(this.context));
return this;
}
});