0

I'm looking for the best way to store a public variable inside a jQuery plugin built on top of the jQuery UI widget factory (jquery.ui.widget.js).

(function($,undefined) {

$.widget('namespace.name',{

    publicVar: '',

    options: {

    },

    _create: function() {

        console.log(this.publicVar);
    },

    publicMethod: function() {

    },

});

})(jQuery);

The variable need to be unique to each instance of the plugin so it needs to be declared somewhere inside the widget object $.widget('namespace.name',{});. Furthermore I want it to be accessible from within each method (_create, publicMethod).

So what I tried is declaring the variable 'publicVar' directly inside the widget Object together with the options and methods. This seems to work but there is no way to access this variable outside of the widget, or is there?

Any suggestions on how to better define public variables for jQuery widgets are welcomed.

1 Answer 1

2

I think your looking for the getter/setter methods that are built into the ui framework. Check the Setters and Getters section of the jQuery UI Developer Guide

look for the part about overriding _SetOption

  _setOption: function(key, value) {
    // handle new settings and update options hash
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Great link you're pointing out. Isn't _setOption for setting and getting options? I have some variables I don't want to be writable but still readable.
You could create specific methods as accessors for each variable you want to be read, or you could override the option function and make it ignore set calls for your protected variables. I'm curious as to way your so concerned about limiting access the internal state so much? I know its all well and good OO practice, but this is javascript that is run client side in what should always be considered a very hostile environment, If someone wants to muck with your internal variables they can and will.
I understand your point. My concern is not that someone has access to the variable but that the API may confuse the users of my plugin. For example, one of the variables is the width of an element (it's cached). Why would any user of a plugin want to define the width when it can be retrieved automatically by the plugin with the width() function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.