Dylan Falconer
Dylan Falconer

Reputation: 81

Functional Programming in JavaScript - events

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?

Upvotes: 8

Views: 2335

Answers (1)

Chatterji Neerugatti
Chatterji Neerugatti

Reputation: 399

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`));

Upvotes: 6

Related Questions