0

I am trying to create a singleton object as a model for a view on backbone, and I want to re-render the view whenever this singleton object is being changed and updated. I am not sure the following code would be the right way of doing it or not

Model

define(function(require) {
     var Singleton = require("modules/Singleton");
     var Singleton = null;
     var SingletonHolder = {

        init: function() {
           Singleton = new Singleton();
           return Singleton.fetch();
        },

        current: function() {
           return Singleton;
        },

        refresh: function() {
           return Singleton.fetch();
        }
     };

    return SingletonHolder;
});

Controller

var currentObj = SingletonHolder.current();
var tempView = new TempView({
            model: currentObj
}); 

View

var TempView = Backbone.View.extend({
    initialize: function() {
         this.listenTo(this.model, "change", this.render);
    }

    render: function() {
         ...
    }

});

For some reasons it doesn't work. Did i miss anything ? I also tried to call Singleton.refresh which it goes to the server side and fetches the latest data from the database, but it doesn't detect the changes and re-render the view.

peter
  • 8,333
  • 17
  • 71
  • 94

1 Answers1

1

You don't have to define a Singleton if you already use requirejs.

Singleton:

define(['models/foo'], function(FooModel){
  return new FooModel;
})

Controller:

define(['foosingleton', 'tempview'], function(fooSingleton, TempView){
  var tempView = new TempView({
    model: fooSingleton
  }); 
});

Here is a similar question: Is it a bad practice to use the requireJS module as a singleton?

Community
  • 1
  • 1
xzhang
  • 563
  • 6
  • 18