0

I am new to backbone js and require js.

I use requirejS to organize my backbone code into modules. I don't know if this has any importance to what I want though. I want to have a central model where all my views will have access to. They should be able to get and set values. I don't want to use it as each view model though. I need to keep in memory search options, user status (logged in/out) etc.

Any ideas?

EDIT

Maybe the answer is here?

Share resources across different amd modules

Community
  • 1
  • 1
chchrist
  • 18,854
  • 11
  • 48
  • 82

2 Answers2

4

If I've understood well what you want I'll say you don't need anything special to having one Model in several Views, just do it:

// code simplified and no tested
App.Model = Backbone.Model.extend({});
App.View  = Backbone.View.extend({});

var myModel = new App.Model();
var viewOne = new App.View({ model: myModel });
var viewTwo = new App.View({ model: myModel });

Updated after comment explanation

You can pass custom parameter to the View.initialize:

// code simplified and no tested
App.Model       = Backbone.Model.extend({});
App.CommonModel = Backbone.Model.extend({});

App.View = Backbone.View.extend({
  initialize: function( opts ){
    this.commonModel = opts.commonModel;
  }
});

var myModelOne    = new App.Model();
var myModelTwo    = new App.Model();
var myCommonModel = new App.CommonModel();

var viewOne = new App.View({ model: myModelOne, commonModel: myCommonModel });
var viewTwo = new App.View({ model: myModelTwo, commonModel: myCommonModel });
fguillen
  • 36,125
  • 23
  • 149
  • 210
2

With requirejs, I would create a module that defines a singleton model, let's say app/settings.js

define(['backbone'], function (Backbone) {
    var Settings = Backbone.Model.extend({
    });

    return new Settings();
});

and pull it in my other modules, for example

define(['backbone', 'app/settings'], function (Backbone, settings) {
    settings.set("pref", "my pref");
});

Subsequent calls to app/settings.js will return the same object.

nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • So actually with requireJS we don't need namespaces? – chchrist Apr 03 '12 at 10:23
  • @chchrist require.js modules act as namespaces of a sort, protecting the global from pollution and providing a hook for future references. With that in mind, yes, I think namespaces aren't needed with require. – nikoshr Apr 03 '12 at 10:32