使用lodash _.memoize与_.random

时间:2018-01-24 10:53:45

标签: javascript angularjs lodash memoization

我看到这个代码由某人(在angularjs中)编写,我想知道这是如何工作的(只是询问我的知识):

    $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
            return !!_.random(0, 4);
        });
    };
    $scope.changeVisibility()

和视图的额外HTML(使用changeVisibility和visibility):

<button ng-click="changeVisibility()">Visibility change</button>
<div class="row">
  <div class="col" visible="visibility(1)">
    1. Row, 1. Col
  </div>

  <div class="col" visible="visibility(2)">
    Mark Hane<br>
    28 yearold<br>
    234 SG
  </div>

  <div class="col" visible="visibility(3)">
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 1. Row --  1<br>
      1. Row, 3. Col, 1. Row --  2
    </div>
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 2. Row --  1<br>
      1. Row, 3. Col, 2. Row --  2<br>
      1. Row, 3. Col, 2. Row --  3
    </div>
  </div>
</div>
... so on to  visibility(9)
</div>
</html>

有人能告诉我吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

如果它在visibility函数中滚动 0 ,我相信隐藏部分内容。基本上,隐藏1 / X的可能性很小,其中X是_.random(0,X)中的最高范围。它将此生成的数字存储在缓存中,用于_.memoize的特定索引(可能减少每个观察者的$ digest循环可执行文件)。

以下是类似的代码,以了解其工作原理(Plunker):

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<body ng-app="app">
  <div ng-controller="myCtrl">
    <button ng-click="changeVisibility()">Visibility change</button>
    <div ng-repeat="i in [1,2,3,4,5,6,7,8,9,10]">
      visibility({{$index+1}}) - {{visibility($index+1)}}
      <span ng-if="visibility($index+1)">- [i c u]</span>
    </div>
  </div>
  <script>
    var app = angular.module('app', []);
    app.controller('myCtrl', function($scope) {
      $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
          return !!_.random(0, 10);
        });
      };
      $scope.changeVisibility(); // initialise 
    });
  </script>
</body>

</html>