最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make a model global for backbone.marionette - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Oct 8, 2013 at 15:49 Jordan SimonJordan Simon 2891 gold badge4 silver badges14 bronze badges 2
  • Is it an instance of the model, or the model definition that you need to access in multiple places ? – thibauts Commented Oct 8, 2013 at 17:07
  • Well I do the same thing, I will just have one global variable called "app", any thing needs to be stored on global, I just add to app. – Ravi Hamsa Commented Oct 8, 2013 at 18:10
Add a ment  | 

3 Answers 3

Reset to default 4

I remend 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');

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();
  });
});

I ended up doing this

MyApp.addInitializer(function(){
    this.currentUser = new UserModel();
});
发布评论

评论列表(0)

  1. 暂无评论