如何将Backbone Views默认设置为单例?

bod*_*ser 2 javascript singleton amd backbone.js

我的所有Backbone.Views只在最终状态下使用一次.(项目视图除外).

目前我以这种方式处理Backbone.Views作为Singleton:

var Singletonizer = function(Singleton) {
    if (Singleton._instance) return Singleton._instance;

    Singleton._instance = new Singleton();

    Singletonizer(Singleton);
};
Run Code Online (Sandbox Code Playgroud)

不幸的是,将这个小函数作为依赖项添加到我的存储库中的每个amd模块并不是一件好事.

还有另一种方法来处理这个问题吗?也许覆盖基础视图类?

Geo*_*pty 6

让你的模块返回一个除了你的视图构造函数之外的函数,一个返回它的单个实例的函数,与下面不同.这样,当您加载模块时,无论您是否喜欢,都不会自动获取实例.相反,在加载我们的"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;
    }
});
Run Code Online (Sandbox Code Playgroud)