Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone/RequireJS model data storage

I am using Backbone/RequireJS to provide my application with modularization and structure. One thing I am coming up against, and would greatly appreciate some advice in this area.

When a user visits the page, the first thing that happens is some JSON that populates a couple of models. I would like these models to be available where-ever I am in the app, as they contain the data and support for the program. Is it permissible to use window.modelName, or do you recommend another/better way of accomplishing this?

like image 599
Joseph at SwiftOtter Avatar asked Jun 16 '26 00:06

Joseph at SwiftOtter


1 Answers

Using your suggested solution defies the whole purpose of using AMD in the first place. Define a module (let's call it globals) as such:

define(function (require) {
  var globals = function () {
    return {};
  };
  return globals();
});

Now, when you init you can add values to it:

globals = require('globals');
globals.mymodel = new MyModel();
mymodel.fetch();

Later, and from any other module, you can access your globals module:

globals = require('globals');
console.log(globals.mymodel.get('myattr');
like image 68
ggozad Avatar answered Jun 19 '26 13:06

ggozad