1

I am pretty much a novice in javascript programming and i would really need some help/advice.

What i am trying to do: I have a function (or object?!) which looks like this:

var svgInteraction = function (containerId) {
    var svgNamespace = "http://www.w3.org/2000/svg",
        htmlns = "http://www.w3.org/1999/xhtml",
    mathns = "http://www.w3.org/1998/Math/MathML";

    svgInteractions = {};

    svgInteractions[containerId] = "I am " + containerId;
    console.log(svgInteractions);

    return function () {
        console.log(svgInteractions);
    }
};

i initialize a variable like this:

var svg1 = svgInteraction("container_1");
var svg2 = svgInteraction("container_2");

The problem is that, for each initialization of the svgInteraction, the svgInteractions objects reinitialize.

It outputs:

Object { container_1="I am container_1"}
Object { container_2="I am container_2"}

Is there any way to keep old values inside it?

Thank you

1 Answer 1

1

Don't set it to an empty object each time (svgInteractions = {}) the function is called.

Try this...

var svgInteraction = (function() {

   var svgInteractions = {};

   return function(containerId) {
     // Implementation
   }

})();

Here, svgInteractions is encapsulated but it will also be static for all calls to svgInteraction.

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

2 Comments

Thank you. All the implementation code should be inside of return function right? It is like a init() ? Another question: How can i keep independent variables/functions for each initialization? For example, i want a different 'click' function to be executed depending on the container. I was thinking about something like svgInteractions[containerId].clickfunction = function() { ... }
@GavanCatalin Yep, you are correct. Anything you want to be initialised per call should be in the function body.

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.