allow for this context binding
This commit is contained in:
@ -2,18 +2,23 @@
|
|||||||
|
|
||||||
Ensures a function is called only once.
|
Ensures a function is called only once.
|
||||||
|
|
||||||
Utilizing a closure, use a flag, `called`, and set it to `true` once the function is called for the first time, preventing it from being called again.
|
Utilizing a closure, use a flag, `called`, and set it to `true` once the function is called for the first time, preventing it from being called again. In order to allow the function to have its `this` context changed (such as in an event listener), the `function` keyword must be used, and the supplied function must have the context applied.
|
||||||
Allow the function to be supplied with an arbitrary number of arguments using the spread (`...`) operator.
|
Allow the function to be supplied with an arbitrary number of arguments using the rest/spread (`...`) operator.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const once = fn =>
|
const once = fn => {
|
||||||
(called => (...args) => (!called ? ((called = true), fn(...args)) : undefined))();
|
let called = false;
|
||||||
```
|
return function(...args) {
|
||||||
|
if (called) return;
|
||||||
```js
|
called = true;
|
||||||
const startApp = event => {
|
return fn.apply(this, args);
|
||||||
// initializes the app
|
};
|
||||||
console.log(event); // access to any arguments supplied
|
|
||||||
};
|
};
|
||||||
document.addEventListener('click', once(startApp)); // only runs `startApp` once upon click
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
const startApp = function(event) {
|
||||||
|
console.log(this, event); // document.body, MouseEvent
|
||||||
|
};
|
||||||
|
document.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user