tags:

views:

63

answers:

2

Hi Guys,

I have a script which creates a user-defined object like this:

obj = new Tree();

This object is always present and interacting with the user.

I want to create a button on the page which, if pressed, should retrieve this object, make some changes to the object and call some methods.

If this were a DOM object, I could have used any of getElementById() or getElementByTagName() etc. However, this object is created in the script and I need to access it in another part on user intervention. Further, making the object global is not an option. Does anybody know how it may be done?

+1  A: 

You will need to make the object accessible from some part of the event handling function. So while making the object itself global is not an option (which is a good move), presumably there's some top-level object which is global to the page for your application? Something like a namespace object, or an OurPageScript object, something like that? In that case, setting the tree as a property of this object will allow for it to be dereferenced later by the event handlers.

If you absolutely cannot have any variables that are accessible from anywhere across the page, things get more tricky. In that case, you will need by definition to provide the event handlers with a reference to your object (because they won't be able to get it themselves). The only way I can think of to do this is to rewrite the handlers every time the object changes; setting them to a closure that includes the object, and invokes the actual handler with this object as a parameter.

A middle ground might be to give the appearance of a global variable by declaring that all event handlers will be invoked in a closure environment where var_tree is defined. That way you wouldn't need to actually mutate the handlers, just repackage them in an appropriate closure whenever the object changed.

(I presume your question was solely about getting access to the object; once the handlers have this, they can modify it and call methods with no further gotchas.)

Andrzej Doyle
+2  A: 

You can attach objects to window if you are defining them inside a different scope than the one you want. This should make it "global". Although I highly suggest fixing your scoping so that var obj exists where it needs to, and not anywhere else.

window.myObj = new Tree();
gnarf