Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Programming in JavaScript - events

Tags:

I've been reading a fair amount about advantages of functional programming, and am trying to write some code which adheres to what might be considered functional programming. Immutability, Pure Functions, Local States, etc.

The particular problem I have is as shown below. I'm not sure if there is some way to do what I want without breaking those rules. I guess I'm here to find that out.

let mouseDown = false;

document.addEventListener('mousedown', () => mouseDown = true);
document.addEventListener('mouseup', () => mouseDown = false);
document.addEventListener('mousemove', e => {
  if (mouseDown) console.log({ x: e.movementX, y: e.movementY });
});

After spending 10+ years working with OOP, I'm finding it very hard to get a hand of FP. However, that's beside the point.

So, my questions are:

  1. Is there a better way to solve this particular problem using functional programming?
  2. Should we be concerned about using functional programming everywhere?
like image 843
Dylan Falconer Avatar asked Oct 30 '16 08:10

Dylan Falconer


1 Answers

Rxjs will fit in here for the code

http://reactivex.io/rxjs/manual/overview.html

Normally you register event listeners.

var button = document.querySelector('button');
button.addEventListener('click', () => console.log('Clicked!'));

Using RxJS you create an observable instead.

var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
  .subscribe(() => console.log('Clicked!'));

What makes RxJS powerful is its ability to produce values using pure functions. That means your code is less prone to errors.

Purity

var count = 0;
var button = document.querySelector('button');
button.addEventListener('click', () => console.log(`Clicked ${++count} times`));

Using RxJS you isolate the state.

var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
  .scan(count => count + 1, 0)
  .subscribe(count => console.log(`Clicked ${count} times`));
like image 183
Victor Avatar answered Sep 24 '22 14:09

Victor