Jordan Simon
Jordan Simon

Reputation: 289

Make a model global for backbone.marionette

I have user model which needs to be accessed in multiple views all over the site. Can I create a global model in a marionette application?

So i can access it through:

window.MarionetteApp.userModel

This is the only idea I've had so far that makes sense. Unless someone has a better way to structure a user in backbone.marionette, im open to ideas.

Upvotes: 4

Views: 2549

Answers (3)

user2902350
user2902350

Reputation: 66

the good example wrote David Sulc:

ContactManager.module("Entities", function(Entities, ContactManager, Backbone, Marionette, $, _){
  Entities.Header = Backbone.Model.extend({
    initialize: function(){
      var selectable = new Backbone.Picky.Selectable(this);
      _.extend(this, selectable);
    }
  });

  Entities.HeaderCollection = Backbone.Collection.extend({
    model: Entities.Header,

    initialize: function(){
      var singleSelect = new Backbone.Picky.SingleSelect(this);
      _.extend(this, singleSelect);
    }
  });

  var initializeHeaders = function(){
    Entities.headers = new Entities.HeaderCollection([
      { name: "Contacts", url: "contacts", navigationTrigger: "contacts:list" },
      { name: "About", url: "about", navigationTrigger: "about:show" }
    ]);
  };

  var API = {
    getHeaders: function(){
      if(Entities.headers === undefined){
        initializeHeaders();
      }
      return Entities.headers;
    }
  };

  ContactManager.reqres.setHandler("header:entities", function(){
    return API.getHeaders();
  });
});

Upvotes: 2

Jordan Simon
Jordan Simon

Reputation: 289

I ended up doing this

MyApp.addInitializer(function(){
    this.currentUser = new UserModel();
});

Upvotes: 0

gbsice
gbsice

Reputation: 541

I recommend using Marionette.RequestReponse. With it, you can do something like this:

MarionetteApp.reqres.setHandler('currentUser', function() {
   if(MarionetteApp.currentUser) return MarionetteApp.currentUser;

   var user = MarionetteApp.currentUser = new MarionetteApp.models.User(/* whatever */);
   return user;
});

And then get your model like so:

var user = MarionetteApp.request('currentUser');

Upvotes: 4

Related Questions