Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton model in Backbone multipage app with RequireJS

I have a Backbone multipage app written with the use of RequireJS. Since it's multipage I decided not to use a router as it got too messy. I've tried multiple ways of creating a singleton object to be used throughout the app

var singletonModel= Backbone.Model.extend({

}),
return new singletonModel;

For the above I'm just referencing the singletonModel model in my class using the define method and then calling it as is

this.singleton = singletonModel;
this.singleton.set({'test': 'test'});

On a module on my next page when I then call something similar to

this.singleton = singletonModel;
var test = this.singleton.get('test');

The singleton object seems to get re-initialized and the test object is null

var singletonModel= Backbone.Model.extend({

}, {
    singleton: null,
    getSingletonModelInst: function () {
        singletonModel.singleton =
            singletonModel.singleton || new singletonModel;
        return singletonModel.singleton;
}

});
return singletonModel;

For the above I'm just referencing the singletonModel model in my class using the define method and then calling it as is

this.singleton = singletonModel.getSingletonModelInst();
this.singleton.set({'test': 'test'});

On a module on my next page when I then call something similar to

this.singleton = singletonModel.getSingletonModelInst();
var test = this.singleton.get('test');

Again it looks like the singleton object is getting re-initialized and the test object is null.

I'm wondering if the issue is because I'm using a multi-page app with no router so state is not been preserved? Has anyone tried using a singleton object in a multi-page app before? If so did you do anything different to how it's implemented on a single-page app?

Thanks, Derm

like image 844
dermd Avatar asked Dec 15 '22 10:12

dermd


1 Answers

Bart's answer is very good, but what it's not saying is how to create a singleton using require.js. The answer is short, simply return an object already instanciated :

define([], function() {

   var singleton = function() {
      // will be called only once
   }

   return new singleton()
})

Here we don't have a singleton anymore :

define([], function() {

   var klass = function() {
      // will be called every time the module is required
   }

   return klass
})
like image 172
julesbou Avatar answered Jan 02 '23 04:01

julesbou