Can you explain the distinction between init() and window.init()?

After reviewing the recipe on how to connect an AngularJS frontend with a Google Cloud Endpoints backend, I still have questions about the AngularJS and Cloud Endpoints initialization process. The relevant section in question is as follows:

Appendix: Tips on AngularJS + Cloud Endpoints Initialization Tip #1: Pay attention to the order of initialization

In the guestbook app, three JS libraries are loaded in a specific sequence:

  • AngularJS
  • The guestbook app
  • Google API Client, which includes Endpoints functionalities

To adhere to this order, the index.html file includes the following <script> tags within the <head> tag to load each JS library:

<script src="js/angular.min.js"></script>  
<script src="js/guestbook.js"></script>  
<script src="https://apis.google.com/js/client.js?onload=init"></script>

Once loaded, the third library (Google API Client) calls the initialization function specified by its ‘onload’ parameter, which is expected to be the init() function. Tip #2: Dive into the AngularJS environment as soon as possible

During initialization, two functions are used:

init() function
window.init() function

The init() function is defined in guestbook.js as follows:

function init() {   window.init(); }

As seen in the code snippet above, this function simply calls the window.init() function (which is the init() function defined globally in the window object) and nothing else. The window.init() function is defined within the AngularJS controller as shown below:

$window.init= function() {   
   $scope.$apply($scope.load_guestbook_lib);
};

In AngularJS, the global window object is accessed using the “$window” notation as a wrapper for it. It is a recommended practice in AngularJS to avoid direct access to the window object for better testability.

The reason for delaying the execution of the initialization in the first init() method is to move as much code as possible into the AngularJS realm, including controllers, services, and directives. This allows you to leverage the full potential of AngularJS and efficiently conduct unit tests, integration tests, and more.

It appears that a global function called init() is defined within an external JavaScript file. This init() function simply triggers window.init() (expected to be triggered by the Google client library after loading). However, isn't window.init() essentially the globally defined init() function? Would this not result in a loop until window.init() (and therefore init()) is redefined?

Answer №1

In this instance, the aim is to catch the initialization event from the Google API and pass it to the AngularJS scope for handling.

Upon loading

<script src="https://apis.google.com/js/client.js?onload=init"></script>

the init function called globally triggers the init method from the window object, which seamlessly integrates with AngularJS due to its access to angular scopes.

This approach simplifies the encapsulation of cloud endpoint calls within promises.

For a more streamlined process, check out the following link:

Answer №2

Within guestbook.js, an init function is defined that seems to have a global scope. This init function is then passed to the google client.js. The global init function simply invokes another global function located at window.init. The initial angular module that is loaded should have established window.init through the $window provided by Angular. There is no looping involved; instead, client.js invokes guestbook.js's init, which in turn calls the angular method $window.init, essentially the same as window.init.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Is it false to say that false in Javascript is still false?

After conducting some research, it appears that the question I have in mind has not been asked before, or maybe it has slipped under my radar. A rational approach would be to consider the following logic: false && false === true false && true === false t ...

Concealing the pathway to a background image

Currently, I have a large grid made up of divs that display different sections of an image. By using background-image and background-position, I am able to showcase parts of the image. However, one issue is that users can easily view the complete image by ...

Error encountered while attempting to compile transcluded directives during unit testing with Angular version 1.3.0

I am facing an issue with a custom directive having transclude: true property. The directive contains a template pointing to a simple HTML file with an anchor element having an ng-transclude attribute. The anchor element wraps the content of the directive. ...

What is the functionality of Mongoose for handling multiple updates?

Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

My objective is to modify a JSON object based on the chosen value from a dropdown menu

Here is the code snippet I have created using HTML: <select style="width:100px;" data-nodrag ng-model="conditions" ng-change="changingCondition(this)"> <option value="and">and</option> <option value="or">or</option> & ...

Personalize the jquery autocomplete outcome

I'm currently utilizing jQuery autocomplete along with a remote data source. $( "input#searchbar" ).autocomplete({ source: function( request, response ) { $.ajax({type: "post", mode: "abort", dataType: ...

Tips for displaying an image using the image tag in jQuery

I am looking to dynamically append a share button image after every image tag that meets certain criteria. For the code snippet and demonstration, you can visit this fiddler link here. $(document).ready(function() { $("img").each(function() ...

"Automate the process of manual content duplication with JavaScript's for each replacement

Seeking a solution to automate the selection process without writing individual JS scripts for every input. For instance, having 10 double inputs (total of 20 inputs) and utilizing the each() function or other methods by only declaring selectors. Find th ...

Why does a basic multiline regex work in ECMAScript but not in .NET?

Currently, I am working on a small utility program in C# that aims to enhance all of my Visual Studio C# item templates by adding extra using ; statements. To achieve this, I have developed a simple regular expression to extract the existing namespace impo ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

What could be causing my ES6 code to fail compilation post npm install?

Check out my npm module built with es6 on Github here. Within the package.json file, there are scripts designed to ensure proper building of the es6 modules. When using npm publish and npm install within the module's directory, everything works fine. ...

What may be causing my Ajax call to get stuck at readystate 1 and not progress further

I've double-checked all my code, yet I'm not getting any response from my Ajax call. Can someone help me figure out what's wrong? function fetchPokemonData() { const apiRequest = new XMLHttpRequest(); apiRequest.open('GET', &apo ...

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Audio playback system in Node.js

I'm looking to create a seamless playlist of mp3 files that play one after the other. While it may seem straightforward, I'm facing challenges keeping the decoder and speaker channel open to stream new mp3 data in once a song finishes playing. Be ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Tips for preventing a span from disappearing when a hidden div is displayed during onmouseover

, there is a concern about the disappearing behavior of the span with ID "topnavbar" when the display property changes from none to block on a hidden div using onmouseover event. The query is how to ensure that the span remains visible at all times. Additi ...