我所有的 Backbone.Views 在它们的最终状态下只使用一次。 (项目 View 除外)。
目前我以这种方式将 Backbone.Views 作为 Singleton 处理:
var Singletonizer = function(Singleton) {
if (Singleton._instance) return Singleton._instance;
Singleton._instance = new Singleton();
Singletonizer(Singleton);
};
不幸的是,将这个小函数作为依赖项添加到我的存储库中的每个 amd 模块并不是很好。
还有其他方法可以解决这个问题吗?也许覆盖基 View 类?
最佳答案
只需让您的模块在 View 构造函数之外返回一个函数,该函数返回它的单个实例,与以下内容不同。这样,当您加载模块时,无论您喜欢与否,您都不会自动获得一个实例。相反,在加载我们的“FailedXhrView”模块后,我们通过调用 FailedXhrView()
'use strict';
define(['jquery',
'underscore',
'backbone',
'text!templates/failedXhr.html'],
function($, _, Backbone, failedXhrTemplate) {
var FailedXhrView = Backbone.View.extend({
el : $('#failedxhr-modal-container'),
template : _.template(failedXhrTemplate),
render : function() {
this.$el.html(this.template({}));
this.$el.find('failedxhr-modal-containee').modal();
return this;
}
});
var instance;
return function() {
if (!instance) {
instance = new FailedXhrView();
}
return instance;
}
});
关于javascript - 如何默认将主干 View 设置为单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219244/