0

How can I store data for a widget? I tried creating variables, but all instances seem to use the same variables, so if I set a var in the first instance - say with a selector to cache it for quick access, the second instance then has access to the cached selecion in the first.

How can I store things similiar to instance properties in a jquery widget?

RISC OS 3
  • 17
  • 5
  • 1
    Store information in `data` attributes on the element used to instantiate the widget. – Rory McCrossan Jan 20 '15 at 15:33
  • I know about data() but that seems like the wrong thing to do... a lot of the time I'm just caching selections or logging boolean states of things, I don't want to to have to call data everytime I need the boolean state of something! There must be another way of doing it? – RISC OS 3 Jan 20 '15 at 15:34
  • 1
    Most plugins store an instance of the JavaScript class (and all its properties) in a single data value (named based on the plugin). – iCollect.it Ltd Jan 20 '15 at 15:36
  • I usually store all of said information in the instance's options object. The widget instance is also usually stored on the .data() of the target element. – Kevin B Jan 20 '15 at 15:41
  • I have just found after more searching that you shouldn't define the vars in the widget itself as they then become part of the prototype properties used by all widget instances, instead, if you create the properties in a method the values stored in them are unique to each widget instance! See: http://stackoverflow.com/questions/13867704/proper-way-to-create-an-instance-variable-using-jquery-ui-widget-factory – RISC OS 3 Jan 20 '15 at 15:51
  • That seems reasonable. (I use TypeScript myself, so just write it like I would C#. I use a base class to provide the "plugin" wiring for all my plugins). – iCollect.it Ltd Jan 20 '15 at 15:54

0 Answers0