Armin kheirkhahan
Armin kheirkhahan

Reputation: 291

self-executing anonymous functions and call it again

I want to do something like this:

var build= (function(){
  //my function body     
})();

function test(){
   //somthing then call build
   build() //i want to call build function again in my code
}

How can I do this? I tried this in angular:

var buildRoot = (() => {

                $SubNode.get({
                    TypeID: vendorAdminService.NodeType.Category
                }, function(data: vendorAdminService.IGetNodeParameters) {
                    $scope.ProductTree = data.TreeNodeModelItem;
                    $scope.AjaxLoading = false;

                }, function(err) {
                    // alert(err)
                })
        })();
$mdDialog.show(confirm).then(function() {
                $Category.Remove(node.ID)
                buildRoot
            }, function() {

            }); 

but it does not work. Anybody can guide me??

Upvotes: 3

Views: 567

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386680

Just use a named function.

Your IIFE needs to return a function, for later calling. But then is no need for an anonymous function.

function build() {
     //my function body
}

or

var build = function () {
         //my function body
    };

Upvotes: 1

Hubert.B
Hubert.B

Reputation: 1

I see that there are missing semi-colons ";"

$mdDialog.show(confirm).then(function() {
            $Category.Remove(node.ID);
            buildRoot();
        }, function() {

        }); 

Upvotes: 0

GibboK
GibboK

Reputation: 73938

You need to return a function in your IIFE. If you IIF is not trivial and has many functionalities you could also consider using Reveal Module Pattern.

var build = (function() {
  var f = function() {
    console.log('hello');
  };
  f();
  return f;
})();

function test() {
  build();
}

test();

Upvotes: 1

roberrrt-s
roberrrt-s

Reputation: 8210

var build = (function() {

    var init = function() {
        // magic code
    };

    return {
        init: init
    }

}());

function test() {
    build.init()
}

test();

You include all your functionalities inside your build object, and you'll be able to call them as soon as you return them from inside that object. This effectively is called the revealing module pattern

For more information, read this

Upvotes: 0

Related Questions