【问题标题】:How to prevent Javascript to be fired multiple times如何防止Javascript被多次触发
【发布时间】:2017-07-05 20:01:41
【问题描述】:

您好,我有一个需要根据条件启用或禁用的按钮。 当它需要被禁用时,我需要显示一条消息。但是 Javascript 会触发很多次,因此消息在只需要显示一次时会显示多次。

以下是调用 Javascript 函数的标记:-

<button type="submit" class="btn btn-save nm" ng-click="controller.saveOpportunity()" ng-disabled="!(controller.canDealBeClosedByFeeAllocationStatus() && controller.isEnabled('SaveOpportunity'))">
                <svg><use xlink:href="../Content/images/c/svg-defs.svg#circle-check"></use></svg>
                Save
            </button>

下面是Javascript函数:-

canDealBeClosedByFeeAllocationStatus:()->
    if this.isReibDeal() && this.data.OpportunitySalesStageIsClose() == true
      if this.data.FeeAllocationComplete == false
        ShowMessage('warning', 'Fee Allocation needs to be complete')
      return this.data.FeeAllocationComplete
    else
      return true

这个问题的解决方法是什么?

【问题讨论】:

    标签: angularjs html coffeescript


    【解决方案1】:

    使用 ng-disabled

    <button ng-disabled="IsDisabled" type="submit" class="btn btn-save nm" ng-click="controller.saveOpportunity()" ng-disabled="!(controller.canDealBeClosedByFeeAllocationStatus() && controller.isEnabled('SaveOpportunity'))">
                    <svg><use xlink:href="../Content/images/c/svg-defs.svg#circle-check"></use></svg>
                    Save
                </button>
    

    在你的控制器中

    $scope.isDisabled=false;
    

    在您的 Javascript 函数中 设置$scope.IsDisabled=true;

    当函数执行一次时 设置$scope.IsDisabled=true

    【讨论】:

      【解决方案2】:

      你不应该有这么大的函数来检查某些东西是否被禁用,因为 ng-disabled 可能会多次检查该方法。

      ng-disabled 可能会被触发,例如,即使您在与 ng-disabled 方法 see console in this example 无关的东西上使用 ng-click 也是如此。

      var app = angular.module('plunker', []);
      
      app.controller('MainCtrl', function($scope) {
        $scope.testClick = function(){
          console.log("click which does not affect disabled flag");
        };
      $scope.isDisabled=function(){
         console.log("disabled check function triggered");
         return true
         
       };
      });
      <!DOCTYPE html>
      <html ng-app="plunker">
      
        <head>
          <meta charset="utf-8" />
          <title>AngularJS Plunker</title>
          <script>document.write('<base href="' + document.location + '" />');</script>
          <link rel="stylesheet" href="style.css" />
          <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
          <script src="app.js"></script>
        </head>
      
        <body ng-controller="MainCtrl">
          <p>Hello {{name}}!</p>
          <div>
             <button ng-click="testClick()">Test</button>
            <button ng-disabled="isDisabled()">Test</button>
            Test {{message}}
          </div>
          
        </body>
      
      </html>

      因此,更好的方法是让 ng-disable 监听一个标志变量,例如 isDealBeClosedByFee,您可以在此过程中或在控制器初始化时对其进行更新。

      【讨论】: