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!

1
  • 2
    You can store private data on the instance itself, for example, inside the _create, you should be able to do this.instanceVar = "huzzah!" Commented Dec 13, 2012 at 20:16

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

You can also declare a private instance variable just like you would a function by using the underscore prefix as a convention. _instanceVar: undefined,
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.
Note also that although the option member doesn't have an underscore, the docs indicate access to its contents via the .option() method: api.jqueryui.com/jquery.widget/#method-option

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.