我对 Backbone 非常陌生,并且正在努力解决在视图之间切换时如何取消绑定元素事件。
到目前为止,我有一个加载和渲染视图的路由器......
define([
"underscore",
"backbone"
], function (_, Backbone) {
"use strict";
var Router = Backbone.Router.extend({
"views": {},
"routes": {
"bugs": "listBugs",
"*other": "showDashboard"
},
"listBugs": function () {
var oRouter = this;
require([
"views/bugs/list"
], function (View) {
oRouter.views.bugsList = new View();
oRouter.views.bugsList.render();
});
},
"showDashboard": function () {
var oRouter = this;
require([
"views/dashboard"
], function (View) {
oRouter.views.dashboard = new View();
oRouter.views.dashboard.render();
});
}
});
return Router;
});
我正在玩仪表板视图中的事件......
/* views/dashboard */
define([
"underscore",
"backbone",
"text!templates/dashboard.html"
], function (_, Backbone, sTemplate) {
"use strict";
return Backbone.View.extend({
"el": "main",
"template": _.template(sTemplate),
"events": {
"click p": "testFunc"
},
"render": function() {
var sHtml;
sHtml = this.template();
this.$el.html(sHtml);
},
"testFunc": function () {
console.log("!");
}
});
});
问题是,如果我在 / 和 /bugs 之间单击几次,然后单击 ap 标签,则会将多行写入控制台(因为正在多次创建仪表板视图),并且如果我在错误查看一行被写入控制台。
当用户离开仪表板时,解除该点击事件的最佳(也是最简单)的方法是什么?
这是错误视图,没什么大不了的...
/* views/bugs/list */
define([
"underscore",
"backbone",
"text!templates/bugs/list.html"
], function (_, Backbone, sTemplate) {
"use strict";
return Backbone.View.extend({
"el": "main",
"template": _.template(sTemplate),
"render": function() {
var sHtml;
sHtml = this.template();
this.$el.html(sHtml);
}
});
});
如果有人感兴趣,我的解决方案
/* Router */
define([
"underscore",
"backbone"
], function (_, Backbone) {
"use strict";
var Router = Backbone.Router.extend({
"mainView": undefined,
"routes": {
"bugs": "listBugs",
"*other": "showDashboard"
},
"renderView": function (oView) {
if (typeof this.mainView !== "undefined") {
this.mainView.close();
}
this.mainView = oView;
this.mainView.render();
$("main").html(this.mainView.el);
},
"listBugs": function () {
var oRouter = this;
require([
"views/bugs/list"
], function (View) {
var oView = new View();
oRouter.renderView(oView);
});
},
"showDashboard": function () {
var oRouter = this;
require([
"views/dashboard"
], function (View) {
var oView = new View();
oRouter.renderView(oView);
});
}
});
return Router;
});
.
/* /views/dashboard */
define([
"underscore",
"backbone",
"text!templates/dashboard.html"
], function (_, Backbone, sTemplate) {
"use strict";
return Backbone.View.extend({
"tagName": "div",
"template": _.template(sTemplate),
"events": {
"click p": "testFunc"
},
"render": function() {
var sHtml;
sHtml = this.template();
this.$el.html(sHtml);
},
"testFunc": function () {
console.log("!");
}
});
});
.
/* /views/bugs/list */
define([
"underscore",
"backbone",
"text!templates/bugs/list.html"
], function (_, Backbone, sTemplate) {
"use strict";
return Backbone.View.extend({
"tagName": "div",
"template": _.template(sTemplate),
"render": function() {
var sHtml;
sHtml = this.template();
this.$el.html(sHtml);
}
});
});