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'));