简体   繁体   English

在Angular Controller中立即调用函数,这是一个好习惯吗?

[英]Immediately-Invoked Function inside of an Angular Controller, good practice?

I have recently start using angular, and I'm coding one of my first controllers like that: 我最近开始使用angular,我正在编写我的第一个控制器之一:

'use strict';
angular
  .module('stakeholder')
  .controller('StakeholderViewController', ['$scope','stakeholderViewFactory',
  function($scope, stakeholderViewFactory) {
    $scope.users = [];

    var loadUsersTable = (function(){
        stakeholderViewFactory.getAccessUsers({stakeholderId: 3}).
                  success(function(data, status, headers, config) {
                    $scope.users = data;
                  }).
                  error(function(data, status, headers, config) {
                    //TODO: Alert
                });
            })();

  }
]);

The thing is that I need the loadUsersTable to execute when the page loads, and I thought that using an inmmediatly invoked function could be the best and clearest option, but I can smell that this is not a good move for some reason that I don't know. 问题是我需要loadUsersTable在页面加载时执行,我认为使用inmmediatly调用的函数可能是最好和最清晰的选项,但我可以闻到,这不是一个好的举动,因为某些原因我不喜欢我知道。

Maybe the best option is something like that, although you have to write more: 也许最好的选择是这样的,虽然你必须写更多:

'use strict';
angular
  .module('stakeholder')
  .controller('StakeholderViewController',   ['$scope','stakeholderViewFactory',
  function($scope, stakeholderViewFactory) {
    $scope.users = [];

    var loadUsersTable = function(){
        stakeholderViewFactory.getAccessUsers({stakeholderId: 3}).
                  success(function(data, status, headers, config) {
                    $scope.users = data;
                  }).
                  error(function(data, status, headers, config) {
                    //TODO: Alert
                });
            };
     loadUsersTable();

  }
]);

Could anyone point me the best practice to write this? 有人能指出我写这个的最佳做法吗?

Thanks! 谢谢!

The immediately executed function is a design-pattern ( Javascript Module Pattern ) mostly used to avoid leaking variables and privates into the outer scope (a function scope , not an Angular scope, just to be clear). 立即执行的函数是一个设计模式Javascript模块模式 ),主要用于避免泄漏变量和私有进入外部作用域( 函数作用域 ,而不是Angular作用域,只是为了清楚)。 In this case, you already have a controller function scope, so you don't need this syntax. 在这种情况下,您已经具有控制器功能范围,因此您不需要此语法。

One best practice I encountered is the use of an initialize function, which is called at the end of the controller. 我遇到的一个最佳实践是使用初始化函数,该函数在控制器的末尾调用。

Advantages: 好处:

  • The function name init clearly expresses what it does: run at the initialising of the controller; 函数名init清楚地表达它的作用:在控制器的初始化时运行;
  • You can clearly see all functions that are called. 您可以清楚地看到所有被调用的函数。
  • You can keep your code ordering as you like, grouped by functionality for example. 您可以根据需要保持代码排序,例如按功能分组。

In your case it would look like: 在你的情况下,它看起来像:

'use strict';
angular
  .module('stakeholder')
  .controller('StakeholderViewController',   ['$scope','stakeholderViewFactory',
  function($scope, stakeholderViewFactory) {
    var loadUsersTable;
    $scope.users = [];


    function init(){
        loadUsersTable();
    };

    loadUsersTable = function(){
        stakeholderViewFactory.getAccessUsers({stakeholderId: 3}).
            success(function(data, status, headers, config) {
                $scope.users = data;
            }).
            error(function(data, status, headers, config) {
                //TODO: Alert
            }
        );
    };

    init();
  }
]);

You don't need another function scope, the IIFE doesn't add anything here. 您不需要其他功能范围,IIFE在此处不添加任何内容。 Just put the code directly in the function: 只需将代码直接放在函数中:

'use strict';
angular
  .module('stakeholder')
  .controller('StakeholderViewController', ['$scope','stakeholderViewFactory',
  function($scope, stakeholderViewFactory) {
    $scope.users = [];

    stakeholderViewFactory.getAccessUsers({stakeholderId: 3}).
      success(function(data, status, headers, config) {
        $scope.users = data;
      }).
      error(function(data, status, headers, config) {
        //TODO: Alert
      });

  }
]);

Immediately-Invoked function doesn't have any binds with AngularJS! Immediately-Invoked函数与AngularJS没有任何绑定! It is a JavaScript pattern, and depends on whether you NEED it or not. 它是一种JavaScript模式,取决于您是否需要它。

Check some articles: 检查一些文章:

IIFE's are best practice as it prevents adding variables to global scope to prevent variable and function clashes. IIFE是最佳实践,因为它阻止将变量添加到全局范围以防止变量和函数冲突。 Your question talks about putting an IIFE inside a controller. 您的问题涉及将IIFE放入控制器中。 Putting an IIFE in the controller doesn't really help as your controller isn't adding to global scope anyway and you shouldn't have many variables or functions added to the controller so the chance of having clashes is very small. 将IIFE放在控制器中实际上没有帮助,因为您的控制器无论如何都没有添加到全局范围,并且您不应该在控制器中添加许多变量或功能,因此发生冲突的可能性非常小。

You could use an IIFE to wrap your controller, factories, directives as a good practice as they will prevent adding to global scope. 您可以使用IIFE将控制器,工厂,指令包装为良好实践,因为它们会阻止添加到全局范围。 For example the StakeholderViewController function won't be added to global scope: 例如,StakeholderViewController函数不会添加到全局范围:

(function() {
    'use strict';

    angular
        .module('stakeholder')
        .controller('StakeholderViewController', ['$scope','stakeholderViewFactory', StakeholderViewController]);


    function StakeholderViewController($scope, stakeholderViewFactory) {
    }

}();

There's some good information in John Papa's style guide . John Papa的风格指南中有一些很好的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM