0

I have the following code which runs inside a local function:

var instance = 'vertical' + view;

//make this variable global
window.instance = instance;

instance = new IScroll( '.' + $(contentAdded).find('.vertical').attr('class'), {
...

And this function gets run a few times througout the application, so I can have multiple instances of the IScroll plugin. However I need these 'instances' to be globally accessible, but because they are dynamic... How do I set them? As the code above just creates a global variable called instance rather than create one that is the name of the dynamic variable.

Trying this:

window.'vertical' + view = 'vertical' + view;

Doesn't work because it doesn't like the string... and doing:

var name = 'vertical' + view;
window.name = instance;

Is the same issue and just creates a variable named name...

How can I do this?

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • Does this make any sense `new IScroll( '.' + $(contentAdded).find('.vertical').attr('class') )`? Wouldn't it be easier just to type `new IScroll('.vertical')`? – VisioN Jul 02 '14 at 11:34
  • @VisioN: I'm guessing there's more in the `class` than `vertical`. – Cerbrus Jul 02 '14 at 11:35
  • @Cerbrus Then this approach won't work having `.` as a prefix. – VisioN Jul 02 '14 at 11:36

3 Answers3

1

I think you're looking for this:

var name = 'vertical' + view;
window[name] = instance;

Say, view is "FooBar", then name would be 'verticalFooBar'.

window[name] would result in window['verticalFooBar']

So, window.verticalFooBar would reference that instance.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

Do window['vertical' + view] = ...

p.s. please read Property Accessors on MDN to find out more

Poelinca Dorin
  • 9,577
  • 2
  • 39
  • 43
0

I would go for a factory class generating instances per view.

This way you are not polluting the global namespace and have the instances nicely stored in the factory class. The instances are globally accessible by getting them from the factory class via the get method.

example/dummy implementation:

var IScrollFactory = {
    instances: {},

    /** creates an instance. */
    create: function(view, ...) {
        var instance = new IScroll( '.' + $(contentAdded).find('.vertical').attr('class'), {
            ...
        };
        this.instances[view] = instance;
        return instance;
    },

    /** returns an already created instance by the view. */
    get: function(view) {
        return this.instances[view];
    }
}

var newInstance = IScrollFactory.create("view1", ...);
var getFromFactoryByView = IScrollFactory.get("view1");
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77