Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require js backbone JS global models

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

like image 284
onlineracoon Avatar asked May 29 '12 15:05

onlineracoon


People also ask

Do people still use Backbone JS?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

What is backbone JS model?

Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1. It extends Backbone.

Should I use Backbone JS?

The developers should make use of Backbone JS while developing a single-page Java application. Backbone JS features Model View Framework, which allows much more than structuring JavaScript architecture. It will help the developers eliminate several issues that they might be facing while developing apps.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.


1 Answers

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.

like image 141
obmarg Avatar answered Dec 08 '22 23:12

obmarg