Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare a static/class variable in a jquery ui widget factory widget

Regarding the jquery ui widget factory...

What is the best way to have a static variable/class level variable that is shared amongst all instances?

e.g.

$.widget("ui.staticTest", {
    staticVar:'unchanged',
    test: function(a){
        if(a){
            this.staticVar= a;
        }
        alert(JSON.stringify(this.staticVar));
    }
});

$('#test').staticTest();
$('#parent').staticTest();

$('#test').staticTest('test','changed');
$('#parent').staticTest('test');

in the above, if staticVar were static, $('#parent').staticTest('test'); would alert 'changed' but instead it alerts 'unchanged'.

(this code is on jsfiddle if you wanna have a play: http://jsfiddle.net/alzclarke/Sx8pJ/)

The solutions i can think of myself are ugly:

1) $('body').data('sharedVariable', myData) - this doesn't seem like good practice, what if someone or something clears the body of data 2) store it in the prototype namespace e.g. = $.ui.staticTest.prototype.staticVar = myData; this also rings alarm bells

like image 943
alzclarke Avatar asked Mar 30 '11 09:03

alzclarke


2 Answers

Closures is your answer

(function($) {

var staticVariable = '';

$.widget('ui.newWidget', {
    options: {

    },
    _init: function() {
    }

});

})(jQuery);

staticVariable will only be available in the scope of the widget you just defined since it's wrapped up in a anonymous function that's called immediately (like you should already be doing for your jquery/jquery ui plugins.

like image 97
Eric Pigeon Avatar answered Sep 27 '22 18:09

Eric Pigeon


Seems that widgets have no shared scope. Whatsoever. So what I would do is define a shared object on the jQuery UI object itself, like you propose yourself.

Note: the shared object name should reflect the widget name and namespace.

$.ui.staticShared = { color: "#fff" };

$.widget("ui.static", {
    color: function (o)
    {
        if (typeof o !== "undefined") $.ui.staticShared.color = o;

        return $.ui.staticShared.color;
    }
});

This is as clean as it gets in my eyes. And sure; there's a risk of people overriding the shared object, but it's not as if the world is going to fall apart if that happens.

If you want some sort of fail-safe/feedback on if the shared object is invalid or has been overridden, you could do a check on the object structure on the _init event.

$.widget("ui.static", {
    _init: function ()
    {
        if (typeof $.ui.staticShared === "undefined")
        {
            alert("$.ui.staticShared is required for this plug-in to run");
        }
    },
});

The _init event is fired whenever an instance is created.

like image 22
cllpse Avatar answered Sep 27 '22 18:09

cllpse