Link to home
Start Free TrialLog in
Avatar of OriNetworks
OriNetworks

asked on

Binding Instance Configuration To Dynamic Number of JavaScript Objects

I am developing a reusable javascript component that can potentially be on a page multiple times. The problem I am having is binding a specific instance of this component to an instance of the object that stores it's configuration and functionality. I'm looking for a pattern that will let me do this.

Assuming I have a generic container on a webpage for content:
<div id="SharedContainer"><div>

Open in new window


I want to generate 2 instances of a component so I might have something like this to create 2 instances by telling makeNewComponentInstance in which element to place these new instances and the second parameter passes something unique to that instance:
makeNewComponentInstance( document.getElementById("SharedContainer"), {"instanceCode":12345} );
makeNewComponentInstance( document.getElementById("SharedContainer"), {"instanceCode":67890} );

Open in new window


So I wind up with something like:
<div id="SharedContainer">
  <div>My component1 
     <button onclick="alertMyInstanceCode();">Write To Log</button>
  </div>
  <div>My component2
     <button onclick="alertMyInstanceCode();">Write To Log</button>
  </div> 
</div>

Open in new window


For some reason I can't remember the right pattern to initialize instances on the fly while allowing to bind the configuration to only that instance it was created for. I don't want to try storing as an html object because the state and configuration information for a specific object is much more complex than the example I am giving.

I've done this before when I had control of how many instances I needed so I would just create however many instances of a variable I need to store it.
var myComponent1 = new ComponentInstance( document.getElementById("SharedContainer"), {"instanceCode":12345} );
var myComponent2 = new ComponentInstance( document.getElementById("SharedContainer"), {"instanceCode":67890} );

Open in new window


What is the proper pattern for binding the component html that is output to "remember" a specific instance of it's configuration?

With an unknown number of instances of the component page, I want to click the button an be able to do something like alert(this.configuration.instanceCode) but I don't have a javascript object to reference.
ASKER CERTIFIED SOLUTION
Avatar of Vijaya Kumar
Vijaya Kumar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of OriNetworks
OriNetworks

ASKER

Thank you