12

I'm using the jQuery UI widget factory.

$.widget("myPlugin" , {

    options: {
    },

    _create: function() {
    },

    instanceVar: "huzzah!"

});

On testing, it looks as though instanceVar is actually part of the prototype. So it is the same across all instances of the plugin.

I can fix this by putting instanceVar into options, like so:

$.widget("myPlugin" , {

    options: {
        instanceVar: "huzzah!"
    },

    _create: function() {
    },

});

However that seems odd, as instanceVar is just an internal variable for use by the plugin -- not something the user of the plugin should be able to change.

Is there another (better) way to achieve this?

Thanks for your help!

user1031947
  • 6,294
  • 16
  • 55
  • 88
  • 2
    You can store private data on the instance itself, for example, inside the _create, you should be able to do `this.instanceVar = "huzzah!"` – Kevin B Dec 13 '12 at 20:16

1 Answers1

17

You can store private data on the instance itself, for example, inside the _create, you should be able to do this.instanceVar = "huzzah!"

$.widget("ui.myPlugin", {

    options: {
        foo: "foo"
    },

    _create: function() {
        this.instanceVar = "huzzah!"
    },

    _setOption: function() {
        this.instanceVar = "worky!";
    },

    destroy: function() {
        console.log(this.instanceVar);  
    }

});

$(document).myPlugin().myPlugin("option","foo","bar").myPlugin("destroy"); // "worky"

$("body").myPlugin().myPlugin("destroy"); // "huzzah!

Demo: http://jsfiddle.net/PGUqr/

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 1
    You can also declare a private instance variable just like you would a function by using the underscore prefix as a convention. _instanceVar: undefined, – Geoff Cox Aug 27 '13 at 17:13
  • 3
    It should be noted that using the underscore prefix does not actually prevent access to such 'private' members and methods. You can still access them via $('#myElement').data('pluginName')._foo. What adding the underscore does is to omit that function from being available via the usual way of calling methods on the widget: $('#myElement').pluginName('somePublicFunction'). Once you have a reference to the widget instance you have full access to everything regardless of whether it has a leading underscore. – jinglesthula Feb 14 '14 at 21:32
  • Note also that although the `option` member doesn't have an underscore, the docs indicate access to its contents via the .option() method: https://api.jqueryui.com/jquery.widget/#method-option – jinglesthula Feb 14 '14 at 21:43