HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Lazy singleton with BackboneJS

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
singletonbackbonejslazywith

Problem

I am trying to have a Backbone.Model which is a singleton and I wish to instantiate it lazily. I only need to support modern browsers so please do not worry about the use of ES5 getter.

Is this the simplest way of achieving my goal?

var LazySingleton = function(){
    var _LazySingleton = Backbone.Model.extend({
        defaults: {
            foo: 0
        },
        initialize: function(){
            console.log('I am initializing');
        }
    });

    return {
        _instance: null,
        get instance() {
            if (this._instance === null) {
                this._instance = new _LazySingleton();
            }

            return this._instance;
        }
    };
}();

console.log('LazySingleton has been declared, but not initialized');
LazySingleton.instance.set('foo', 3);        
console.log('foo should be 3:', LazySingleton.instance.get('foo'));

Solution

This is not the simplest way.

  • There seems to be no point in instance, if there can be only 1 instance, why have it all ?



  • Why have initialize at all ?



  • Why set foo to 0, I would set it undefined



-
If I were to keep the instance concept, I would write this:

_instance: null,
get instance() {
    if (this._instance === null) {
        this._instance = new _LazySingleton();
    }

    return this._instance;
}


as

_instance: null,
get instance() {
    return this._instance = this._instance || new _LazySingleton();
}


I would probably go for something like this ( I might have the syntax wrong )

var LazySingleton = Backbone.Model.extend({
    defaults: {
        foo: undefined
    },
    initialize: function(){
    });

Code Snippets

_instance: null,
get instance() {
    if (this._instance === null) {
        this._instance = new _LazySingleton();
    }

    return this._instance;
}
_instance: null,
get instance() {
    return this._instance = this._instance || new _LazySingleton();
}
var LazySingleton = Backbone.Model.extend({
    defaults: {
        foo: undefined
    },
    initialize: function(){
    });

Context

StackExchange Code Review Q#66781, answer score: 2

Revisions (0)

No revisions yet.