Require js trunk JS global models

I want to create a UserSession model that loads and saves the session ID into a cookie using the jQuery cookie plugin.

This is my code for my UserSession model module:

define(['jQuery', 'Underscore', 'Backbone'], function($, _, Backbone){ var UserSession = Backbone.Model.extend({ defaults: { 'accessToken': null, 'userId': null }, initialize: function(){ this.load(); }, authenticated: function(){ return Boolean(this.get('accessToken')); }, save: function(authHash){ $.cookie('userId', authHash.id); $.cookie('accessToken', authHash.accessToken); }, load: function(){ this.userId = $.cookie('userId'); this.accessToken = $.cookie('accessToken'); } }) return UserSession; }); 

But I will say that I want to access it in my login mode:

 define(['jQuery', 'Underscore', 'Backbone', 'text!templates/login.html', 'models/UserLogin', 'models/UserSession'], function($, _, Backbone, loginTemplate, UserLogin, UserSession){ var LoginView = Backbone.View.extend({ model: new UserLogin, el: $('#screen'), events: { 'submit #frm-login': 'login' }, login: function(e){ e.preventDefault(); // Lets not actually submit. this.model.set({ 'username': $('#login-username').val(), 'password': $('#login-password').val() }); this.model.save(null, { success: function(nextModel, response){ // Do something here with UserSession model }, error: function(){ } }); }, render: function(){ $(this.el).html(_.template(loginTemplate, {})); return this; } }); return new LoginView; }); 

The thing is, every time I access the UserSession model in modules (see the callback function of the model.save function), it uses the default values, so I need to have some singleton instance of the UserSession model, how can I do this to do this?

My first idea was to use the application namespace, so in our main.js (the first main module that loads), the UserSession module is also initialized there, and every time another module accesses this module, the main module is required. which has an object that returns an instance of UserSession.

How can this be best done?

thanks

+7
source share
1 answer

Assuming you want to create a single global UserSession in your entire application, I would simply return an instance of UserSession from the UserSession module. This way you will get the same object back whenever you use a UserSession in a define call. for example

 define(['jQuery', 'Underscore', 'Backbone'], function($, _, Backbone){ var UserSession = Backbone.View.extend({ ... }); return new UserSession(); }); 

Then in another place:

 define(['UserSession'], function( UserSession ){ // UserSession in here will be the singleton you created in the UserSession module alert( UserSession.authenticated() ); }); 

Require.js should only run the UserSession module once, regardless of how many times it has been used elsewhere, so the UserSession object you create is effectively a single.

+21
source

All Articles