Question

I'm working on a jQuery UI Widget but i've ran into some problems. This is how i instantiate the plugin.

$('#myId0, #myId1').mywidgetname();

And here is my plugin code:

;(function ( $, window, document, undefined ) {
  $.widget( "namespace.mywidgetname" , {
    _create: function(){
      debugger;
      this._myPrivateProperty = 2;
....

The problem is that when the debugger stops for the second time, I already have this._myPrivateProperty instantiated with value 2. I thought that the widget will be instantiated twice, but this is not the case.

Also, if I specify different options for each element, like so:

$('#myId0').mywidgetname({myVarA: 'someText'});
$('#myId1').mywidgetname({myVarB: 'someText'});

The variable this.options will be different for each one. Does anyone now how to make "private" properties private ?

Thank you

Was it helpful?

Solution

I've found the problem. It seems that shouldn't define properties in your plugin root like so:

;(function ( $, window, document, undefined ) {
  $.widget( "namespace.mywidgetname" , {
    myPrivateVar = {},
    _create: function(){

      this.myPrivateVar.test = 2;
....

This keeps a reference for all the instances. But instead you should declare your variables right inside the _create method.

;(function ( $, window, document, undefined ) {
  $.widget( "namespace.mywidgetname" , {
    _create: function(){
      this.myPrivateVar = {};
      this.myPrivateVar.test = 2;
....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top