David
David

Reputation: 16726

How to share a global variable/object with RequireJS

I'd like to set a variable or object in main.js which I can then reference from any backbone view.

I considered using localStorage, but the data is dynamic and a little sensitive so I wouldn't like to have it stored in localStorage as it could be manipulated by the user very easily.

Upvotes: 0

Views: 414

Answers (2)

Emile Bergeron
Emile Bergeron

Reputation: 17430

@TJ already gave what's needed to achieve what I call a Service within my app, borrowed from AngularJS services. I have a couple services, like i18n which is just a i18next instance.

Like you, I wanted to manage certain data relative to the app that could be shared everywhere, without putting it in the window object.

I came up with a AppState service which is just a Backbone model instance.

define(['underscore', 'backbone', 'color'], function(_, Backbone, Color) {

    var State = Backbone.Model.extend({

        setBrandColor: function(hexColor, options) {
            return this.set({ color: new Color(hexColor) }, options);
        },

        getBrandColor: function() {
            return this.get('color');
        },
    });

    return new State(); // return a new instance instead of the constructor.
});

What's cool with a Backbone model is that anything within the app can listen to its events. This is inspired from React.

this.listenTo(AppState, 'change:color', this.onBrandColorChange);

Note that I prefer to use PascalCase for services even though they're instances, they're closely related to a static type in other languages.

This way, when the app state changes, other parts of the app may or may not react accordingly. Without the events, the app would need to be more coupled which is undesirable.

Upvotes: 0

T J
T J

Reputation: 43156

Since you said "main.js" I think you're confused between RequireJS and Backbone.js. RequireJS is not part of Backbone. It is an AMD module loader which happens to be used a lot with backbone projects.

Looks like you need a RequireJS module like:

define(function (require) {
  var someData;
  var singleton = function () {
    return {
        getMyData = function(){},
        setMyData = function(data){},
    };
  };
  return singleton();
});

P.S: Above code can be made object literal, an instance of proper constructor function, es6 class of whatever. I just posted something as an example.

Upvotes: 1

Related Questions