Lets say I have a javascript library (.js file) which does something like drawing an SVG graph on a div element that is on a page. The library applies business logic and also creates event handlers for when elements are clicked etc. Pseudo-code could look like this:
myLib = {};
myLib.dummy = null;
mylib.doStuff = function(divID) {
//divID is the ID of the element on which SVG graph will be drawn
//does graph drawing and sets up myLib.dummy for feedback or such, e.g.:
myLib.dummy = $("#divID").width();
}
My question is: how do I handle a case where I want to apply this script to 2 (or more) elements on the same page, and then have seperate “instances” of myLib pertaining to each element. I know I cannot do call it like this from the page:
myLib.doStuff('topDiv'); //myLib.dummy will be say 400;
myLib.doStuff('bottomDiv'); //myLib.dummy will be say 600;
With the above code, I will no longer have access to myLib.dummy that pertains to div with ID = ‘topDiv’, since they are using the same namespace.
I suspect I am missing a design pattern or that the answer could be simply a case of namespacing.
I would appreciate any suggestions or help.
There’s many different areas where you could introduct the seperation or indirection. Without knowing more about your usage context, its hard to say what’s a good choice. But the above is one of many working choices.