gpt4 book ai didi

javascript - 如何默认将主干 View 设置为单例?

转载 作者:行者123 更新时间:2023-12-03 22:16:20 25 4
gpt4 key购买 nike

我所有的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com