Search code examples
javascriptbackbone.jssingletonamd

How do I set Backbone Views as singleton by default?


all my Backbone.Views are only used once in their final state. (Except item views).

Currently I handle Backbone.Views as Singleton this way:

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

    Singleton._instance = new Singleton();

    Singletonizer(Singleton);
};

Unfortunately it isn't that nice to add this little function as dependency to each amd module in my repository.

Is there another way to handle this? Maybe overwriting the base view class?


Solution

  • From the very recommendable book Recipes with Backbone:

    From here:

    // definition
    MyApplication.Views.List = Backbone.View.extend();
    
    // instantiation
    $(function() {
      MyApplication.ListView = new MyApplication.Views.List({
        el: $('#list')
      }); 
    })
    

    To here:

    $(function() {
      MyApplication.ListView = new (Backbone.View.extend({
        initialize: function() {
          // ...
        }
      }))({el: $('#list')})
    });
    

    We assign an instantiation of an anonymous class to MyApplication.ListView. In this approach, we are doing the typical extension of a top-level Backbone class with custom attributes and methods. The difference, however, is that we do not assign the result to a class name as we did earlier. Instead, we immediately create a new instance of this anonymous class. Lastly, MyApplication.ListView is assigned to the resulting object.

    I have to say I've never used techniques like this. It looks to messy for me, I prefer legibility than architecture.