|
9 | 9 | angular.module('wu.masonry', [])
|
10 | 10 | .controller('MasonryCtrl', function controller($scope, $element, $timeout) {
|
11 | 11 | var bricks = {};
|
12 |
| - var reloadScheduled = false; |
| 12 | + var schedule = []; |
13 | 13 | var destroyed = false;
|
| 14 | + var timeout = null; |
| 15 | + |
| 16 | + function scheduleMasonryOnce() { |
| 17 | + var args = arguments; |
| 18 | + var found = schedule.filter(function (item) { |
| 19 | + return item[0] === args[0]; |
| 20 | + }).length > 0; |
| 21 | + |
| 22 | + if (!found) { |
| 23 | + scheduleMasonry.apply(null, arguments); |
| 24 | + } |
| 25 | + } |
14 | 26 |
|
15 | 27 | // Make sure it's only executed once within a reasonable time-frame in
|
16 | 28 | // case multiple elements are removed or added at once.
|
17 |
| - function scheduleReload() { |
18 |
| - if (!reloadScheduled) { |
19 |
| - reloadScheduled = true; |
20 |
| - |
21 |
| - $timeout(function relayout() { |
22 |
| - reloadScheduled = false; |
23 |
| - if (!destroyed) { |
24 |
| - $element.masonry('layout'); |
25 |
| - } |
26 |
| - }, 30); |
| 29 | + function scheduleMasonry() { |
| 30 | + if (timeout) { |
| 31 | + $timeout.cancel(timeout); |
27 | 32 | }
|
| 33 | + |
| 34 | + schedule.push([].slice.call(arguments)); |
| 35 | + |
| 36 | + timeout = $timeout(function runMasonry() { |
| 37 | + if (destroyed) { |
| 38 | + return; |
| 39 | + } |
| 40 | + schedule.forEach(function (args) { |
| 41 | + $element.masonry.apply($element, args); |
| 42 | + }); |
| 43 | + schedule = []; |
| 44 | + }, 30); |
28 | 45 | }
|
29 | 46 |
|
30 | 47 | function defaultLoaded($element) {
|
|
38 | 55 |
|
39 | 56 | function _append() {
|
40 | 57 | if (Object.keys(bricks).length === 0) {
|
41 |
| - // Call masonry asynchronously on initialization. |
42 |
| - $timeout(function () { |
43 |
| - $element.masonry('resize'); |
44 |
| - }); |
| 58 | + $element.masonry('resize'); |
45 | 59 | }
|
46 | 60 |
|
47 | 61 | if (bricks[id] === undefined) {
|
|
54 | 68 | // Keep track of added elements.
|
55 | 69 | bricks[id] = true;
|
56 | 70 | $element.masonry('appended', element, true);
|
57 |
| - scheduleReload(); |
| 71 | + scheduleMasonryOnce('layout'); |
58 | 72 | }
|
59 | 73 | }
|
60 | 74 |
|
|
68 | 82 |
|
69 | 83 | delete bricks[id];
|
70 | 84 | $element.masonry('remove', element);
|
71 |
| - |
72 |
| - scheduleReload(); |
| 85 | + scheduleMasonryOnce('layout'); |
73 | 86 | };
|
74 | 87 |
|
75 | 88 | this.destroy = function destroy() {
|
|
0 commit comments