为backbone.marionette创建一个全局模型

时间:2013-10-08 15:49:23

标签: javascript backbone.js marionette

我的用户模型需要在整个站点的多个视图中访问。我可以在木偶应用程序中创建全局模型吗?

所以我可以通过以下方式访问它:

window.MarionetteApp.userModel

这是我迄今为止唯一有意义的想法。除非有人有更好的方法在backbone.marionette中构建用户,否则我会接受想法。

3 个答案:

答案 0 :(得分:4)

我建议使用Marionette.RequestReponse。有了它,你可以这样做:

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

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

然后让你的模型如此:

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

答案 1 :(得分:2)

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

答案 2 :(得分:0)

我最终做了这个

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