Skip to content
This repository was archived by the owner on Dec 30, 2018. It is now read-only.

Commit 9b215d6

Browse files
committed
fix(app): more careful relayout scheduling
1 parent dd408af commit 9b215d6

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

src/angular-masonry.js

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,39 @@
99
angular.module('wu.masonry', [])
1010
.controller('MasonryCtrl', function controller($scope, $element, $timeout) {
1111
var bricks = {};
12-
var reloadScheduled = false;
12+
var schedule = [];
1313
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+
}
1426

1527
// Make sure it's only executed once within a reasonable time-frame in
1628
// 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);
2732
}
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);
2845
}
2946

3047
function defaultLoaded($element) {
@@ -38,10 +55,7 @@
3855

3956
function _append() {
4057
if (Object.keys(bricks).length === 0) {
41-
// Call masonry asynchronously on initialization.
42-
$timeout(function () {
43-
$element.masonry('resize');
44-
});
58+
$element.masonry('resize');
4559
}
4660

4761
if (bricks[id] === undefined) {
@@ -54,7 +68,7 @@
5468
// Keep track of added elements.
5569
bricks[id] = true;
5670
$element.masonry('appended', element, true);
57-
scheduleReload();
71+
scheduleMasonryOnce('layout');
5872
}
5973
}
6074

@@ -68,8 +82,7 @@
6882

6983
delete bricks[id];
7084
$element.masonry('remove', element);
71-
72-
scheduleReload();
85+
scheduleMasonryOnce('layout');
7386
};
7487

7588
this.destroy = function destroy() {

0 commit comments

Comments
 (0)