Caley Woods
Caley Woods

Reputation: 4737

ExtJS4 Singleton not a singleton?

In my app.js file I have a function named createPermissions that goes through an Ext.store called MyAccess and eventually creates a singleton named UserPermissions that contains a list of components a user has access to.

This was my original proof of concept code and I decided on Friday on the way home that I wouldn't be able to use a singleton because as each user launched the app it would overwrite and cause everyone's permissions to be looking at the user who last launched the app which is not what I need.

Here is the code:

createPermissions: function() {
    var access     = Ext.getStore( 'MyAccess' ),
        components = [];

    access.data.items.forEach( function(permission) {
        components.push( permission.data.id.toLowerCase() );
    });

    Ext.define('UserPermissions', {
        singleton  : true,
        components : components
    });
}

In the console after you launch the ExtJS app you can type UserPermissions.components and it will output an array of ID's of components the user has access to (this is expected). I had 2 coworkers launch the all also and execute the same command in their console while I re-ran mine and to my surprise, they all remain different which is NOT what I expected (but is exactly what I need...)

So is ExtJS creating a new app for each user that launches the application? That's the only explanation I can come up with as to why each users "UserPermission" singleton would not truly be a singleton, unless the way ExtJS handles a singleton is different than your everyday implementation.

Upvotes: 1

Views: 127

Answers (1)

rixo
rixo

Reputation: 25001

A singleton is nothing more than a global variable. Now, what is a global variable in javascript?

globalVariable = 'foo';

really means:

window.globalVariables = 'foo';

Try it:

globalVariable = 'bar';
globalVariable === window.globalVariable; // true

Notice we've not even formally assigned window.globalVariable...

So, doing:

Ext.define('UserPermissions', ...);

and later being able to access it this way:

UserPermission.components

just means that Ext has created a window.UserPermission variable for you.

Finally, you probably knows that the window object represents the browser tab. So you can easily conclude that you get one "singleton" per browser tab. As far as I know that's what is called a singleton in any language...

ExtJS is just a client-side library, keep in mind it has no server components. So don't expect to find such powerful feature as "flying variables across computers in 3 lines of code without even having to establish connection between them" ^^

Upvotes: 2

Related Questions