1

I would like to refactor my working code to a better structured javascript. At this moment I have something like this:

function Search(){
    addNode = function(nodeToAdd){
        //do something
    }
    function update(){
        var node = aKindOfObjectFromSomeLibrary;
        node.on('click', function(d){
            $.each(someArray, function(i){
                addNode(this);
            }
        }
    }
}

The objective is to create a Search object with it method that can be used even outside like this:

var s = new Search();
s.addNode(nodeToAdd);

I was thinking about doing this:

function Search(){
    this.addNode = function(nodeToAdd){}
}

But then the function addNode will be not accessible inside a nested generic function.

Another way I was studying is the use of this structure:

(function(){
    var object = {
        var field = itsValue,
        addNode : function(){}
    };
)();

But of course the problem of recalling the method inside a nested structure still remains.

Can you please direct me to the correct way of refactoring my code, is the only way to have that working to pass a

var scope = this
inside the nested function?

I am also referring to this Q&A in stackoverflow: How to "properly" create a custom object in JavaScript?

With the difference that, by now, I don't have to subclass my object (and this is the reason why I tried the

(function(){})();
closure structure.
Community
  • 1
  • 1
Gianmarco
  • 2,536
  • 25
  • 57

1 Answers1

0

Zio, try to structure this way

var util = {

Search : function(node) {
        this.addNode(node);
    },



   addNode : function(node) {

    // do something

}

and when you want to call the function you do:

util.Search(nodetoadd);

but I suggest not to create a function search that just simply call another function (addNode)

Just do:

var util = {

   addNode : function(node) {

        // do something

    }

and call it:

util.addNode(nodetoadd);
Mattew Trincanati
  • 191
  • 1
  • 1
  • 9
  • Search is just the name of the object, not a function that itself will search something... The object will also contain other fields and many other methods, I think the util "static" class is not what I need. – Gianmarco Jun 05 '15 at 12:53