-1

What is the use of 'cb => cb(snapshot)' ?

    if (this._snapshotCallbacks.length > 0) {
            const snapshot = gl.canvas.toDataURL();
            this._snapshotCallbacks.forEach(cb => cb(snapshot));
            this._snapshotCallbacks = [];
    }

    requestSnapshot (callback) {
            this._snapshotCallbacks.push(callback);
    }
Hydrostatic
  • 45
  • 1
  • 5

2 Answers2

0

this._snapshotCallbacks.forEach(cb => cb(snapshot));

means there is a collection of callbacks and the code here invokes them one after each other.

forEach is a function that exists on the array prototype that will take a function as a parameter and invoke this function for each element in the collection. When the function is invoked, the element is passed as the sole argument to the function that forEach took cb => cb(snapshot) is an es6 shorthand function definition.

So in your example, cb is a callback thats then invoked with the snapshot.

Basically, this is the same idea in a forloop

var function1 = (msg) => { alert(msg);}
var function2 = (msg) => { alert(msg.toUpperCase());}

var functions = [function1, function2];
for(var i = 0; i < functions.length; i++){
  var fnToApply = functions[i];
  fnToApply("hello world");
}

in which an array of functions is invoked in a loop, and each function is designed ahead of time to know what it takes as a param

mistahenry
  • 8,064
  • 3
  • 22
  • 36
0
this._snapshotCallbacks.forEach(cb => cb(snapshot));

can be rewritten as

this._snapshotCallbacks.forEach(function (callback) {
   callback(snapshot)
});

i think it's clear when there is no arrow function?

Doğancan Arabacı
  • 3,702
  • 2
  • 14
  • 24