The right way to create an instance variable using jQuery UI Widget Factory

I am using jQuery UI factory widget.

$.widget("myPlugin" , { options: { }, _create: function() { }, instanceVar: "huzzah!" }); 

In testing, it looks as if instanceVar is actually part of the prototype. So this is the same in all instances of the plugin.

I can fix this by adding instanceVar to the parameters, for example:

 $.widget("myPlugin" , { options: { instanceVar: "huzzah!" }, _create: function() { }, }); 

However, this seems strange, since instanceVar is just an internal variable for use by the plugin - not that the plugin user should be able to modify.

Is there any other (better) way to achieve this?

Thank you for your help!

+7
source share
1 answer

You can store personal data in the instance itself, for example, inside _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/

+12
source

All Articles