Alex Rivera | Logout

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

Asked 2011-03-30T09:51:10.400
11

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

Edit
Report

1 Answer

26

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.

answered 2012-05-22T00:48:13.540

Your Answer