coder87
coder87

Reputation: 101

Calling a function from outside of require which is written inside of require in dojo

<html>
<head>    
<script>    
    require(["dojo/ready"],function(ready){

      function init(dataItem) {
          alert("inside init method")
          updateData(dataItem);
      }
      function updateData(dataItem){
       //inside this function, i am creating some breadcrumb and making each part of it a link.
       //Now that link is calling another method outerFunction()
      }
      ready(function(){
          init({
              type: "All Locations",
              id: "All_Locations"
          });
      });
   });

function outerFunction(jsonObj){
    init(jsonObj); // not working

}
</script>
</head>
<body>
   <div>
    </div>
</body>
</html>

So basically i need to call init() from outerFunction(). Please help me in this.

I need to call init() defined above , from outerFunction(). But this is not happening. Initially i tried to keep this outerFunction() inside require block. But then in that case, outerFunction() was not getting called from breadcrumb link.

So i had to move it outside. And now from outside, outerFunction() is getting called but init() is not getting called from outerFunction()

Or if in any way I can write outerFunction method inside require block and can make same call flow.

Solution: I have used dojo.subscribe() inside ready and dojo.publish() in outerFunction(). And it worked for me.

Upvotes: 3

Views: 2404

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44685

Well, it's indeed a scope issue. You can solve it in various ways. One of them is to put outerFunction() inside the require() block like you mentioned.

However, if you call that function from somewhere else, you might encounter a problem. For a breadcrumb link (you mentioned) you could use an onclick handler inside the same require() block, for example:

on(breadcrumbLink, "click", function() {
    outerFunction({});
});

However, as soon as the amount of code increases, you'll have a problem if you put it all into the same require() block (because it will become unmaintainable), so you could split the init() function to a separate module, which can be included for both functions.


A third solution, though it is quite a bad practice if it's done quite often, is to put either one of them on the window scope. If you move the init() function to window, for example:

window.init = init;

Then you can access it from within the outerFunction(). Another way to do this is to move the outerFunction() inside the require() block and adding it to window as well, for example:

require(/** Stuff */, function() {
    function init() { }

    function outerFunction() { }
    window.outerFunction = outerFunction;
});

Upvotes: 3

Related Questions