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

javascript - Require js backbone JS global models - Stack Overflow

programmeradmin2浏览0评论

I want to create a UserSession model, which 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 lets say I want to access it into my login view:

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 each time I access the UserSession model in modules (see the model.save success call back function) it uses default values, so I need to have some kind of singleton instance of the UserSession model, how can I do this?

My first idea was to use the app namespace so in our main.js (first main module that gets loaded) and there initialize the UserSession module, and each time another module access that module, the require the main module which has a object that returns the UserSession instance.

How can this be done best?

Thanks

I want to create a UserSession model, which 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 lets say I want to access it into my login view:

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 each time I access the UserSession model in modules (see the model.save success call back function) it uses default values, so I need to have some kind of singleton instance of the UserSession model, how can I do this?

My first idea was to use the app namespace so in our main.js (first main module that gets loaded) and there initialize the UserSession module, and each time another module access that module, the require the main module which has a object that returns the UserSession instance.

How can this be done best?

Thanks

Share Improve this question asked May 29, 2012 at 15:57 onlineracoononlineracoon 2,9705 gold badges48 silver badges66 bronze badges 2
  • Your first idea seems to be perfect solution. Otherwise, you'd have to store the user-session in localStorage/cookies and such stuff... – Parth Thakkar Commented May 29, 2012 at 16:02
  • how do you generate the session on the server and access it? I want to use the same approach but I am having problems accessing the cookie content. I dont have a login view as this is rendered by the server. – Gambo Commented Jul 30, 2012 at 20:33
Add a comment  | 

1 Answer 1

Reset to default 21

Assuming you want a single global UserSession across your entire application, I would just return an instantiated UserSession from the UserSession module. That way you'll get the same object back whenever you use UserSession in a define call. For example

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

    return new UserSession();
});

Then elsewhere:

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's used elsewhere, so the UserSession object you instantiate in there is effectively a singleton.

发布评论

评论列表(0)

  1. 暂无评论