1

I have widgetA with data structure - d. widgetA initializes widgetB and passes data to widgetB, like

$('<div>').widgetB({d:d});

But, when data in widgetA changes, in widgetB they dont, thats because when passing variables as options, jquery widget factory clones them.

How to pass reference pf variable to widget?

http://jsfiddle.net/sbNUh/

In this example widgetB does not change value and both times prints A.

4 Answers 4

3

Actually i found a trick to pass option by reference, if you reinitialize the widget the option is passed by reference (http://jsfiddle.net/sbNUh/8/).

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

Comments

1

You can pass a function like this

http://jsfiddle.net/sbNUh/1/

// widjet A
self.a = $('<div>').widgetB({ d: function() { return d; }}).appendTo(el);

....

// widjet B
$('#con').append('<div>'+this.options.d().a+'</div>');

This also signals more that you are actively retrieving the latest state

Comments

1

Change d to a function, in this way:

var private_var_d = "A";
function d(set){
    if(typeof set != "undefined") private_var_d = set;
    return private_var_d;
}
(self.a=$('<div>').widgetB({d:d}))

Whenever you want to get the variable, use: this.options.d(). When you want to change the variable, use this.options.d("newvariable").

This method's effectiveness is based on how functions work: Functions can refer to variables which are defined in the same scope of definition. So, function d can always refer to private_var_d, because they're both defined in the same (anonymous) function.

Fiddle: http://jsfiddle.net/sbNUh/2/.

Comments

0

You could try keeping a global variable that each widget uses.

1 Comment

There could be several widgetA widgets and each has his own data and own widgetB widgets.

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.