Let's follow up this discussion at the Neptune Community

(this forum will be kept in read-only mode)

Structuring JS code

Hi,


In the script code, I'm trying to make my JavaScript more module based and thus try to do something like below but it is not able to recognize the module. The below code runs fine in JSFiddle and is able to alert me the callable message but when I run it inside Neptune, it throws the error "Cannot read property 'anotherMethod' of undefined". As soon as I remove the module and put everything in the global space, it works fine but that's not how I want to do it. 


var myModule = (function(){
    var myMethod;
    myMethod = function() {
        alert("callable");
    };

    return {
        anotherMethod: function(){
            myMethod();
        }
    };
}());

And I'm calling the above in the below manner from a button click:


myModule.anotherMethod();


Kindly can you please suggest if something else also needs to be done in order to get this working in Neptune?


Regards,

Gourav


Hello,


Any suggestions please?


Thanks,

Gourav

Hi


Yes. I have tested it and it works as you would like it to. Here is some images to show how I achieved it:


(Using another project atm, so embedded this into it)


Global Script Block:




The on a button I use the press event:




The result is what you expect:




Anything i do wrong ?



Regards

Ole Andre

Hi Gourav


It is very important where you put this coding. If you use the JS code above in press events etc, the myModule will be declared as a local variable. Please drag a HTML5/Script object into your UI Tree. Then you will have the variabel as global, and you can use it.


Regards

Ole Andre

Hello,


Thanks for the screen shots. The only difference to my set up was the script code was right under the App in the UI tree and not within any page as yours. When I put the script code inside a page, I'm able to call it fine on a press event from any page. 


I've some other script codes as well right under the App and they are callable in the manner I was trying to call my above code. So why it is not able to understand the module, defined in a script code element, when it is not defined under any page? Well its not a biggie but will help me to understand more of Neptune.


Thanks,

Gourav 

Hello Ole Andre,


Thanks for your response.


I'm using the above code in an html5/script code object already and is just calling the public api on the press event using "myModule.anotherMethod();". But it still gives me the above error and is not able to recognize the module.


Can you please suggest what could be the issue?


Thanks,

Gourav

Login or Signup to post a comment