Getting and setting values for jQuery widgets
December 11th, 2009If you come from an OOP background you’re likely used to defining class variables like this:
class MyClass { var internalValue1; var internalValue2; function constructor() { … } }
The values which are to be stored in your object are simple, straightforward, likely to be typed, and the compiler will detect typos in the variable names. JavaScript, as a loosely types language which treats its objects more like collections than discrete objects, can’t really offer us those protections. Conversely, that also means that we have a great deal of flexibility.
In essence, we can dynamically subclass our objects, which you have to admit is a neat trick.
So, for jQuery.UI widgets, the variables stored within our widget are not defined until we assign them. The act of assignment defines the variable name, which can then be called upon at will.
Assignment is simply:
this._setData(‘variablename’, variablevalue);
Retrieval of this value is similarly straightforward:
this._getData(‘variablename’);
This does mean that the old problem of misnamed variables is alive and well. It also means that you need to be prepared to handle an undefined response to the _getData call.


