gpt4 book ai didi

javascript - init() 和 window.init() 有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 05:36:18 31 4
gpt4 key购买 nike

我已经通读了以下秘诀,它展示了一种使用 Google Cloud Endpoints 后端为 AngularJS 前端提供动力的方法:

https://cloud.google.com/resources/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications

我不明白的是关于 AngularJS 和 Cloud Endpoints 初始化的附录。相关部分如下:

Appendix: Tips on AngularJS + Cloud Endpoints Initialization Tip #1: Be careful on the initialization sequence

The guestbook app loads three different JS libraries in the following sequence:

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

To follow this sequence, the index.html contains the following <script> tags in the <head> tag for loading each of the JS libraries:

<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. In this case, the init() function is expected and invoked. Tip #2: Enter into the AngularJS world as quickly as possible

In the initialization sequence, we use the two functions:

init() function
window.init() function

This init() function is defined in guestbook.js in the following way:

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

As you can see the code above, the function just calls window.init() function (i.e. init() function defined in the global window object) and does nothing else. The window.init() is defined in the AngularJS controller as follows:

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

In AngularJS, the global window object is accessed by “$window” notation which is a wrapper for it. It is a best practice in AngularJS not to access the window object directly to improve testability.

The reason why you would not want to execute the initialization in the first init() method is so you can put as much of the code as possible in the AngularJS world, such as controllers, services and directives. As a result, you can harness the full power of AngularJS and have all your unit tests, integrations tests,and so forth.

似乎是一个全局函数init()正在外部 javascript 文件中定义。这init()函数只是调用 window.init() (并且应该在加载后由 Google 客户端库调用)。但是 window.init() 不是什么而是全局定义的 init()功能?那么在window.init()之前我们不会在这里得到一个循环吗? (因此 init() )正在被重新定义?

最佳答案

此示例尝试获取 google api init 事件并将其传输到 AngularJS 范围。

什么时候

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

加载后调用全局定义的 init 函数,该函数又调用定义在 window 对象上的 init 方法。由于此函数可以访问 Angular 范围,因此它可以很好地处理 Angular

它使将云端点调用包装在 promises 中变得更加容易

这里是如何让它变得更容易 http://anandsekar.github.io/initialize-google-appengine-and-angularjs/

关于javascript - init() 和 window.init() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537687/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com